开发者

Strange limitation in the implementation of internal interface

I have code

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");
  }
}
开发者_Go百科

Why such strange limitation? I have internal interface and why I can't create internal method in interface realization?


This is because interfaces can't specify anything about the visibility of members, only the members themselves. All members that implement an interface must be public. The same happens when you implement a private interface.

One solution might be explicitly implementing the interface:

internal interface IFoo
{
  void foo();
}

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

In the above code, you must have an instance of A cast to IFoo to be able to call foo(), but you can only do such a cast if you are internal compared to the class and hence have access to IFoo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜