c# – 在初始化列表中分配readonly属性
可以告诉我,为什么它会编译?
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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |