【问题标题】:Strange limitation in the implementation of internal interface内部接口实现的奇怪限制
【发布时间】:2011-09-22 10:26:41
【问题描述】:

我有代码

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");
  }
}

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

【问题讨论】:

  • 你不能有一个暴露在外面的公共类,实现一个不会暴露的内部接口。没有意义。
  • 你有没有尝试显式地实现接口:void IFoo.foo() { /* stuff */ }

标签: c# theory


【解决方案1】:

这是因为接口不能指定任何关于成员可见性的内容,只能指定成员本身。所有实现接口的成员都必须是public。实现private 接口时也会发生同样的情况。

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

internal interface IFoo
{
  void foo();
}

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

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

【讨论】:

  • 从实现中删除“公共”部分 - 它应该只是 void IFoo.foo()
  • 我知道显式接口实现。但我不明白 C# 中的这种限制原因。
  • @JonSkeet 可能比我能解释得更好,他有注意边缘情况的诀窍。我自己也不确定为什么,我只知道是怎么回事。
  • 接口的成员基本上总是是公开的。这很烦人:(事实上,I've blogged about it before now
猜你喜欢
  • 1970-01-01
  • 2012-01-04
  • 2015-07-02
  • 2018-03-11
  • 2018-05-12
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 2019-05-09
相关资源
最近更新 更多