当从拥有 auto 属性的类中调用初始化程序时,为什么可以使用对象初始化程序来设置私有(private) 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;
}
}
最佳答案
setter 上的 private
修饰符表示 - 对封闭类型私有(private)。
也就是说,该属性只能由包含类型设置。
如果不是这种情况,您将永远无法设置该属性,并且它实际上是只读的。
来自 MSDN - private (C# Reference) :
Private members are accessible only within the body of the class or the struct in which they are declared
关于c# - 使用对象初始值设定项设置私有(private) setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10651270/