This question already has an answer here:
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;
}
Because private means "not accessible to other types", not "not accessible to other instances".
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
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