使用对象初始化程序设置私有设置程序 [英] Setting a private setter using an object initializer
问题描述
当从拥有auto属性的类中调用初始值设定项时,为什么可以使用对象初始值设定项来设置私有set auto属性?我以两个班级为例.
Why is it possible to use an object initializer to set a private set auto property, when the initializer is called from within the class which owns the auto property? I have included two class as an example.
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
修饰符表示-封闭类型专用.
The private
modifier on a setter means - private to the enclosing type.
也就是说,该属性只能由包含类型设置.
That is, the property can be set by the containing type only.
如果不是这种情况,您将永远无法设置该属性,并且该属性实际上是只读的.
If this was not the case, you would never be able to set the property and it would effectively be read-only.
从MSDN-私有(C#参考):
私有成员只能在声明它们的类或结构体中访问
Private members are accessible only within the body of the class or the struct in which they are declared
这篇关于使用对象初始化程序设置私有设置程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!