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

前端之家收集整理的这篇文章主要介绍了为什么以接口名为前缀的方法不能在C#中编译?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下为什么不编译?
  1. interface IFoo
  2. {
  3. void Foo();
  4. }
  5.  
  6. class FooClass : IFoo
  7. {
  8. void IFoo.Foo() { return; }
  9.  
  10. void Another() {
  11. Foo(); // ERROR
  12. }
  13. }

编译器抱怨“当前上下文中不存在名称’FooMethod’”.

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

  1. public void Foo() { return; }

编译得很好.

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

解决方法

因为当您“显式实现”接口时,您只能通过强制转换为接口类型来访问该方法.隐式转换将找不到该方法.
  1. void Another()
  2. {
  3. IFoo f = (IFoo)this:
  4. f.Foo();
  5. }

进一步阅读:

C# Interfaces. Implicit implementation versus Explicit implementation

猜你在找的C#相关文章