我明确地创建并实现了一个接口(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/