c# - 使用对象初始值设定项设置私有(private) setter

标签 c# .net initialization automatic-properties object-initializers

当从拥有 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/

相关文章:

java - 变量未初始化

c - 在 while 循环条件中赋值

c# - 在 C# 中高效查找二维数组 T[][] 中的唯一元素

c# - 存储库作为工厂?

c# - 设置AllowAutoRedirect = false仍然遵循重定向

.net - JavaScriptSerializer UTC DateTime 问题

objective-c - objC 中的 initWith 与 arrayWith?

C# task.Start() 不运行该方法

c# - 查找字符串中包含属性值的 XmlNode

c# - 当此信息与对象参数一起传递时,为什么 Enum.GetName() 要求类型?