【问题标题】:Why can I call a private method on another instance than itself [duplicate]为什么我可以在另一个实例上调用私有方法而不是它本身[重复]
【发布时间】:2017-03-21 10:02:26
【问题描述】:

我想知道为什么在 C# 中允许以下内容:

当我用 private 方法定义一个类 MyClass 时。让我们调用它的实例A。现在我在它的一个公共方法中创建了一个MyClass 的实例。此实例称为B。所以BA 中的一个实例,两者都是同一类型。

我可以从A 调用B 上的这个私有方法。 对我来说,该方法是私有的,这意味着只有 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;
    }
}

谢谢!

【问题讨论】:

  • private 的范围是类,而不是实例。
  • 如你所说,没有其他课程! B 属于 MyClass 类型,您可以访问它在 MyClass 中的私有成员。这很简单。
  • 谢谢,现在清楚了!

标签: c# oop


【解决方案1】:

B.MyPrivateMethod(); 是允许的,因为该方法是在 MyClass 类中的方法内调用的。

您将无法在 MyClass 类中的方法之外调用 MyPrivateMethod(),但是因为PublicMethodCreatingB 在同一个类中,所以它可以访问所有私有方法和变量。

【讨论】:

  • 谢谢,帮了我大忙!
猜你喜欢
  • 1970-01-01
  • 2012-10-23
  • 2013-12-01
  • 1970-01-01
  • 2012-06-29
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多