从同一类的不同实例设置受保护/私有属性 [英] Setting protected/private properties from a different instance of the same class

查看:91
本文介绍了从同一类的不同实例设置受保护/私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含具有私有集和受保护集可访问性级别集的属性的类,是否可以在同一类的另一个实例上更改这些属性?

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.

例如:

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


推荐答案

是。访问权限是 type ,而不是实例。这对于实现相等性之类的事情尤其有用,因为您可以测试 this.x == other.x&&。 this.y == other.y; 。还可以访问嵌套类型。

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.

这篇关于从同一类的不同实例设置受保护/私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆