内部接口实现中的奇怪限制

本文关键字:接口 实现 内部 | 更新日期: 2023-09-27 18:09:15

我有代码

internal interface IFoo
{
  void foo();
}
public class A : IFoo
{
  // error CS0737: 'A' does not implement interface member 'IFoo.foo()'. 
  //'A.foo()' cannot implement an interface member because it is not public.
  internal void foo()
  {
    Console.WriteLine("A");
  }
}

为什么有这样奇怪的限制?我有内部接口,为什么我不能在接口实现中创建内部方法?

内部接口实现中的奇怪限制

这是因为接口不能指定成员的可见性,只能指定成员本身。实现一个接口的所有成员必须是public。在实现private接口时也会发生同样的情况。

一个解决方案可能是显式地实现接口:

internal interface IFoo
{
  void foo();
}
public class A : IFoo
{
  void IFoo.foo()
  {
    Console.WriteLine("A");
  }
}

在上面的代码中,你必须有一个A的实例转换为IFoo才能调用foo(),但是你只能做这样的转换,如果你是internal相比类,因此可以访问IFoo