Setting a private setter using an object initializer

感情迁移 提交于 2020-02-28 06:25:48

问题


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;
    }
}

回答1:


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.

From MSDN - private (C# Reference):

Private members are accessible only within the body of the class or the struct in which they are declared




回答2:


Because private means accessible within the class that owns property.



来源:https://stackoverflow.com/questions/10651270/setting-a-private-setter-using-an-object-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!