Setting protected/private properties from a different instance of the same class

久未见 提交于 2019-12-11 09:56:32

问题


If I have a class that contains properties with private set and protected set accessibility levels set, will I be able to change those properties on another instance of the same class?

Note: I'm not on a machine which I can test this on right now, otherwise I'd just run the code below.

For instance:

public class Foo
{
    public string A {get; private set;}
    public string B {get; protected set;}

    public void Bar() 
    {
        var someOtherFoo = new Foo();

        // Does this change someOtherFoo's A?
        someOtherFoo.A = "A";

        // Does this change someOtherFoo's B?
        someOtherFoo.B = "B";
    }
}

回答1:


Yes. The access is to the type, not the instance. This is especially useful for things like implementing equality, as you can test this.x == other.x && this.y == other.y;. Access is also available to nested types.




回答2:


Short answer : Yes




回答3:


// Does this change someOtherFoo's A? // Does this change someOtherFoo's B?

Yes and yes.



来源:https://stackoverflow.com/questions/2568576/setting-protected-private-properties-from-a-different-instance-of-the-same-class

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