在使用C#的时候,我最近意识到我可以从Foo的静态函数,甚至从其他Foo对象调用一个Foo对象的私有函数.在我学到关于访问修饰符的一切之后,这对我来说听起来很奇怪.
据我所知,当某项功能属于某种内部流程的一部分时,您将私有功能.只有对象本身知道何时才能使用这些功能,因为其他对象不应该/不能控制对象的流.是否有任何理由,为什么同一类的其他对象应该从这个非常简单的规则中除外?
根据请求,一个例子:
- public class AClass {
- private void doSomething() { /* Do something here */ }
- public void aFunction() {
- AClass f = new AClass();
- f.doSomething(); // I would have expected this line to cause an access error.
- }
- }
解决方法
当一个成员私有时,它对其他类是私有的而不是类本身.
它可以是有用的,例如,如果你有一个Equals方法需要访问另一个实例的私有成员:
- public class AClass
- {
- private int privateMemberA;
- // This version of Equals has been simplified
- // for the purpose of exemplifying my point,it shouldn't be copied as is
- public override bool Equals(object obj)
- {
- var otherInstance = obj as AClass;
- if (otherInstance == null)
- {
- return null;
- }
- return otherInstance.privateMemberA == this.privateMemberA;
- }
- }