开发者

Setting properties with {} braces when instantiating

开发者 https://www.devze.com 2023-03-12 05:48 出处:网络
Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB?

Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB?

public class ClassA {
    public string ID { get; private set; }

    public void test() {
        var instanceA = new ClassA() { ID = "42" };
        var instanceB = new ClassB() { ID = "43" };开发者_运维知识库
    }

    public class ClassB {
        public string ID { get; private set; }
    }
}

Thanks


test() is a member of ClassA, so it has access to the private members (and the setter) of A. It does not have access to the private members or setters of ClassB, hence the error on instanceB but not instanceA.

For more on accessibility of private members, I encourage you to see this answer on a related question.


Your Test method is in Class A so that can be accessed.


Class B is inside Class A, A cannot access private members of B just because of the composition.

0

精彩评论

暂无评论...
验证码 换一张
取 消