为什么下面的不编译?
interface IFoo
{
void Foo();
}
class FooClass : IFoo
{
void IFoo.Foo() { return; }
void Another() {
Foo(); // ERROR
}
}
编译器提示“名称‘FooMethod’在当前上下文中不存在”。
但是,如果将 Foo 方法更改为:
public void Foo() { return; }
这编译得很好。
我不明白为什么一个有效而另一个无效。
最佳答案
因为当您“显式实现”一个接口(interface)时,您只能通过转换为接口(interface)类型来访问该方法。隐式转换将找不到方法。
void Another()
{
IFoo f = (IFoo)this:
f.Foo();
}
进一步阅读:
C# Interfaces. Implicit implementation versus Explicit implementation
关于c# - 为什么以接口(interface)名称为前缀的方法在 C# 中无法编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3347839/