我有代码
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");
}
}
Run Code Online (Sandbox Code Playgroud)
为何如此奇怪的限制?我有内部接口,为什么我不能在接口实现中创建内部方法?
这是因为接口无法指定有关成员可见性的任何内容,只能指定成员本身.实现接口的所有成员必须是public.实现private接口时也会发生同样的情况.
一种解决方案可能是明确实现接口:
internal interface IFoo
{
void foo();
}
public class A : IFoo
{
void IFoo.foo()
{
Console.WriteLine("A");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,你必须有一个A强制转换的实例IFoo才能调用foo(),但如果你要internal与类进行比较并且因此可以访问,那么你只能进行这样的强制转换IFoo.