以下为什么不编译?
- interface IFoo
- {
- void Foo();
- }
- class FooClass : IFoo
- {
- void IFoo.Foo() { return; }
- void Another() {
- Foo(); // ERROR
- }
- }
编译器抱怨“当前上下文中不存在名称’FooMethod’”.
但是,如果将Foo方法更改为:
- public void Foo() { return; }
编译得很好.
我不明白为什么一个有效,另一个没有.
解决方法
因为当您“显式实现”接口时,您只能通过强制转换为接口类型来访问该方法.隐式转换将找不到该方法.
- void Another()
- {
- IFoo f = (IFoo)this:
- f.Foo();
- }
进一步阅读:
C# Interfaces. Implicit implementation versus Explicit implementation