Lee*_*ite 17 c# class object access-modifiers
在使用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.
}
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*ens 12
当你将一个成员设为私有时,它对其他类是私有的而不是类本身.
例如,如果您有一个需要访问另一个实例的私有成员的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;
}
}
Run Code Online (Sandbox Code Playgroud)