Why are my privates accessible?

后端 未结 5 805
温柔的废话
温柔的废话 2021-01-19 05:47

I have the following code:

public class PersonInitializer
{
    private Person _person;

    public static Person LoadFromFile(string path)
    {
        Per         


        
5条回答
  •  终归单人心
    2021-01-19 06:31

    It is accessible, because you are the class it is defined in!

    Access modifiers apply to classes, not to instances of a class. That means, an instance of class A has access to all private members of another instance of class A.

    I assume, you agree with me, that this is ok:

    var p = this._person;
    

    But what about this:

    public void DoSomething(PersonInitializer personInitializer)
    {
        var p = personInitializer._person;
    }
    

    According to your assumption, this code would be valid depending on the input.
    Example:

    DoSomething(this); // ok
    DoSomething(other); // not ok
    

    This makes no sense :-)

提交回复
热议问题