有人能告诉我,它到底为什么要编译吗?
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 规范中是这样描述的:
A member initializer that specifies an object initializer after the equals sign is a nested object initializer - that is, an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.
所以这段代码:
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;
关于c# - 分配给初始化列表中的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15784483/