簡體   English   中英

在初始化列表中分配readonly屬性

[英]Assignment to readonly property in initializer list

可以告訴我,為什么它會編譯?

namespace ManagedConsoleSketchbook
{
    public interface IMyInterface
    {
        int IntfProp
        {
            get;
            set;
        }
    }

    public class MyClass
    {
        private IMyInterface field = null;

        public IMyInterface Property
        {
            get
            {
                return field;
            }
        }
    }

    public class Program
    {
        public static void Method(MyClass @class)
        {
            Console.WriteLine(@class.Property.IntfProp.ToString());
        }

        public static void Main(string[] args)
        {
            // ************
            // *** Here ***
            // ************

            // Assignment to read-only property? wth?

            Method(new MyClass { Property = { IntfProp = 5 }});
        }
    }
}

這是一個嵌套的對象初始值設定項 它在C#4規范中描述如下:

在等號后面指定對象初始值設定項的成員初始值設定項是嵌套對象初始值設定項 - 即嵌入對象的初始化。 而不是為字段或屬性分配新值,嵌套對象初始值設定項中的賦值被視為對字段或屬性成員的賦值。 嵌套對象初始值設定項不能應用於具有值類型的屬性,也不能應用於具有值類型的只讀字段。

所以這段代碼:

MyClass foo = new MyClass { Property = { IntfProp = 5 }};

相當於:

MyClass tmp = new MyClass();

// Call the *getter* of Property, but the *setter* of IntfProp
tmp.Property.IntfProp = 5;

MyClass foo = tmp;

因為您正在使用使用ItfProp的setter的初始化ItfProp而不是 Property的setter。

因此它將在運行時拋出NullReferenceException ,因為Property仍然為null

因為

int IntfProp {
    get;
    set;
}

不是只讀。

你沒有調用MyClass.Property setter,只是getter。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM