为什么这个私有方法会从另一个类执行?

Jen*_*iya 5 c# private

我明确地创建并实现了一个接口,如下所示.

public interface IA
{
    void Print();
}

public class C : IA
{
    void IA.Print()
    {
        Console.WriteLine("Print method invoked");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后执行以下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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

打印方法是私有的

调用了Print方法

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

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

Jon*_*eet 6

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

好吧,这只是排序的私人.它使用显式接口实现 - 可以通过接口访问,但只能通过接口访问.所以,即使在C级,如果你有:

C c = new C();
c.Print();
Run Code Online (Sandbox Code Playgroud)

那将无法编译,但是

IA c = new C();
c.Print();
Run Code Online (Sandbox Code Playgroud)

......随处可见,因为界面是公开的.

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

显式接口成员实现具有与其他成员不同的可访问性特征.因为显式接口成员实现永远不能通过方法调用或属性访问中的完全限定名来访问,所以它们在某种意义上是私有的.但是,由于它们可以通过接口实例访问,因此它们在某种意义上也是公开的.