c# - 为什么以接口(interface)名称为前缀的方法在 C# 中无法编译?

标签 c# interface

为什么下面的不编译?

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/

相关文章:

c# - MySql 不接受 float 列中的 C# float.MinValue

c# - 将类视为使用接口(interface)定义的类

c# - 显式地将基类转换为派生类

c# - 使用 postsharp 在类中调用替代方法

c# - 根据子元素值选择父 XML 元素 LINQ C#

C# 实现接口(interface)定义的派生类型?

function - typescript 接口(interface) : function as property - or - this in interface implementations

WPF HiercharchicalDataTemplate.DataType : How to react on interfaces?

c# - 使用 C# 反射调用构造函数

c# - 带分组依据和字符串变量的 LINQ 动态查询