C# 初始值设定项列表中只读属性的赋值

C# 初始值设定项列表中只读属性的赋值,c#,properties,readonly,initializer-list,C#,Properties,Readonly,Initializer List,有人能告诉我,为什么它会编译 namespace ManagedConsoleSketchbook { public interface IMyInterface { int IntfProp { get; set; } } public class MyClass { private IMyInterface field = null;

有人能告诉我,为什么它会编译

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 }});
        }
    }
}

因为您使用的初始值设定项使用的是
ItfProp的setter
不是
属性的setter

因此,它将在运行时抛出一个
NullReferenceException
,因为
Property
仍然是
null

这是一个嵌套对象初始值设定项。在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;
因为

int IntfProp {
    get;
    set;
}
这不是只读的


您没有调用
MyClass.Property
的setter,只是调用getter

你能详细说明一下吗?标准是如何涵盖这种情况的?等等,启动visual studio,发布一些澄清的示例啊,Jon在家里,我无法与他竞争:p@Spook,请不要弄错,
属性
仍将是
null
。好的,现在已经清楚了。不过,这是一个令人困惑的语法。