Why can I call a private method of another instance of the same type outside of that instance? [duplicate]

痴心易碎 提交于 2019-12-04 03:27:15

问题


If I have ObjectA, and it has a private method GetPrice() and also has a "parent" field of the same type, why am I able to call GetPrice() on the parent instance from within the child instance?

Example:

private decimal GetPrice()
{
    ObjectA parent = Parent;

    if(parent != null)
    {
        return parent.GetPrice(); // Why is this OK?
    }

    return 0;
}

回答1:


Because private means "not accessible to other types", not "not accessible to other instances".




回答2:


Because private scope is limited to the class, not the instance as defined in the C# spec:

1.6.2 Accessibility Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following table.

Accessibility       Meaning   

public              Access not limited   
protected           Access limited to this class or classes derived from this class  
internal            Access limited to this program   
protected internal  Access limited to this program or classes derived from this class    
private             Access limited to this class



回答3:


An access modifier is related to it's implementing class/type not to instances of that class



来源:https://stackoverflow.com/questions/13195891/why-can-i-call-a-private-method-of-another-instance-of-the-same-type-outside-of

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