为什么以接口名为前缀的方法不能在C#中编译?

tgi*_*hil 6 c# interface

以下为什么不编译?

interface IFoo
{
void Foo();
}

class FooClass : IFoo
{
void IFoo.Foo() { return; }

void Another() {
   Foo();  // ERROR
 }
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨"当前上下文中不存在名称'FooMethod'".

但是,如果将Foo方法更改为:

 public void Foo() { return; }
Run Code Online (Sandbox Code Playgroud)

编译得很好.

我不明白为什么一个有效,另一个没有.

Ada*_*rth 10

因为当您"显式实现"接口时,您只能通过强制转换为接口类型来访问该方法.隐式转换将找不到该方法.

void Another()
{
   IFoo f = (IFoo)this:
   f.Foo();
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

C#接口.隐式实现与显式实现