我想知道为什么在C#中允许以下内容:
当我MyClass用私有方法定义一个类时.让我们调用它的实例A.现在我MyClass在其中一个公共方法中创建一个实例.调用此实例B.所以B是A同一类型的实例.
我可以调用这个私有方法B的A.对我来说,这个方法是私有的,只能B称之为自己而不是其他类.显然,同一类型的另一个类也可以调用它B.
为什么是这样?它与private关键字的确切含义有关吗?
代码示例:
public class MyClass
{
private static int _instanceCounter = 0;
public MyClass()
{
_instanceCounter++;
Console.WriteLine("Created instance of MyClass: " + _instanceCounter.ToString());
}
private void MyPrivateMethod()
{
Console.WriteLine("Call to MyPrivateMethod: " + _instanceCounter.ToString());
}
public MyClass PublicMethodCreatingB()
{
Console.WriteLine("Start call to PublicMethodCreatingB: " + _instanceCounter.ToString());
MyClass B = new MyClass();
B.MyPrivateMethod(); // => ** Why is this allowed? **
return B;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
B.MyPrivateMethod();是允许的,因为该方法是在MyClass类中的方法中调用的.
您将无法MyPrivateMethod()在MyClass类中的方法之外调用,但因为PublicMethodCreatingB它位于同一个类中,所以可以访问所有私有方法和变量.