当从拥有 auto 属性的类中调用初始化器时,为什么可以使用对象初始化器来设置私有 set auto 属性?我以两个类为例。
public class MyClass
{
public string myName { get; private set; }
public string myId { get; set; }
public static MyClass GetSampleObject()
{
MyClass mc = new MyClass
{
myName = "Whatever", // <- works
myId = "1234"
};
return mc;
}
}
public class MyOtherClass
{
public static MyClass GetSampleObject()
{
MyClass mc = new MyClass
{
myName = "Whatever", // <- fails
myId = "1234"
};
return mc;
}
}
Run Code Online (Sandbox Code Playgroud) .net c# initialization automatic-properties object-initializers
我有一个Manager有两个属性的类,如下所示:
public class Manager()
{
private string _name;
private List<int> _reportingEmployeesIds;
public string Name { get { return _name; }}
public List<int> ReportingEmployeesIds { get {return _reportingEmployeesIds; } }
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建Manager类的实例,如下所示
Manager m = new Manager
{
Name = "Dave", // error, expected
ReportingEmployeesIds = {2345, 432, 521} // no compile error - why?
};
Run Code Online (Sandbox Code Playgroud)
两个属性都缺少set属性,但编译器允许设置ReportingEmployeesIds,但不允许设置Name属性(错误:属性或索引器Manager.Name不能分配给它,它只是readonly).
为什么会这样?为什么编译器不会抱怨ReportingEmployeesIds只读.