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

前端之家收集整理的这篇文章主要介绍了为什么以接口名为前缀的方法不能在C#中编译?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下为什么不编译?
interface IFoo
{
void Foo();
}

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

void Another() {
   Foo();  // ERROR
 }
}@H_403_3@ 
 

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

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

public void Foo() { return; }@H_403_3@ 
 

编译得很好.

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

解决方法

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

进一步阅读:

C# Interfaces. Implicit implementation versus Explicit implementation

原文链接:https://www.f2er.com/csharp/97363.html

猜你在找的C#相关文章