c# - 为什么这个私有(private)方法确实从另一个类中执行?

标签 c# private

我明确地创建并实现了一个接口(interface),如下所示。

public interface IA
{
    void Print();
}

public class C : IA
{
    void IA.Print()
    {
        Console.WriteLine("Print method invoked");
    }
}

然后按照Main方法执行

public class Program
{
    public static void Main()
    {
        IA c = new C();
        C c1 = new C();
        foreach (var methodInfo in c.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            if (methodInfo.Name == "ConsoleApplication1.IA.Print")
            {
                if (methodInfo.IsPrivate)
                {
                    Console.WriteLine("Print method is private");
                }
            }
        }
        
        c.Print();
    }
}

我在控制台上得到的结果是:

Print method is private

Print method invoked

所以我的问题是为什么这个私有(private)方法是从其他类执行的?

据我所知,私有(private)成员的可访问性仅限于其声明类型,那么为什么它的行为如此奇怪。

最佳答案

So my question is why this private method got executed from other class?

好吧,它只是有点私有(private)的。它正在使用 explicit interface implementation - 它可以通过界面访问,但只能通过界面访问。所以即使在 C 类中,如果你有:

C c = new C();
c.Print();

那会编译失败,但是

IA c = new C();
c.Print();

...这将适用于任何地方,因为接口(interface)是公开的。

C# 规范 (13.4.1) 指出显式接口(interface)实现在访问方面是不常见的:

Explicit interface member implementations have different accessibility characteristics than other members. Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public.

关于c# - 为什么这个私有(private)方法确实从另一个类中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30619569/

相关文章:

javascript - JavaScript 中的 private 和 public 这两个词到底有多保守

java - 为什么在方法中看不到 "private static"?

c# - 测试策略建议——需要记录运行方法的验证结果并将其用于测试目的

message - Telegram Bot 对成员(member)耳语

database - swift : Save public CKRecord to private database

c# - 在运行时编译 C# 代码 [更新 : or Alternatives]

C++:另一个类中的类作为类型?

c# - 命名空间中不存在名称 "XamlDisplay"

c# - .cs 页面上的 html 按钮

C# MySQLDataReader 在结果中替换