为什么这个私有方法确实从另一个 class 执行?
Why this private method does get executed from another class?
我明确地创建并实现了一个接口,如下所示。
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
所以我的问题是为什么这个私有方法从其他 class 执行?
据我了解,私有成员的可访问性仅限于其声明类型,那么为什么它的行为如此奇怪。
So my question is why this private method got executed from other class?
嗯,它只是 某种 私人的。它使用 explicit interface implementation - 它可以通过界面访问,但只能通过界面访问。所以即使在 class C 中,如果你有:
C c = new C();
c.Print();
编译失败,但是
IA c = new C();
c.Print();
...这将适用于任何地方,因为接口是 public。
C# 规范 (13.4.1) 指出显式接口实现在访问方面是不常见的:
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.
我明确地创建并实现了一个接口,如下所示。
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
所以我的问题是为什么这个私有方法从其他 class 执行?
据我了解,私有成员的可访问性仅限于其声明类型,那么为什么它的行为如此奇怪。
So my question is why this private method got executed from other class?
嗯,它只是 某种 私人的。它使用 explicit interface implementation - 它可以通过界面访问,但只能通过界面访问。所以即使在 class C 中,如果你有:
C c = new C();
c.Print();
编译失败,但是
IA c = new C();
c.Print();
...这将适用于任何地方,因为接口是 public。
C# 规范 (13.4.1) 指出显式接口实现在访问方面是不常见的:
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.