代码之家  ›  专栏  ›  技术社区  ›  Kevin Pang

从同一类的不同实例设置受保护/专用属性

  •  1
  • Kevin Pang  · 技术社区  · 15 年前

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

    注意:我现在不在可以测试的机器上,否则我只运行下面的代码。

    例如:

    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";
        }
    }
    
    3 回复  |  直到 15 年前
        1
  •  4
  •   Marc Gravell    15 年前

    对。通道是 类型 ,而不是实例。这对于实现平等尤其有用,因为您可以测试 this.x == other.x && this.y == other.y; . 也可以访问 嵌套的 类型。

        2
  •  1
  •   rep_movsd    15 年前

    简短回答:是的

        3
  •  0
  •   heisenberg    15 年前

    /这改变了其他人的想法吗? //这会改变其他人的B吗?

    是的,是的。