举个例子:
public interface IFoo
{
IFoo Bar();
}
public class Foo : IFoo
{
public Foo Bar()
{
//...
}
IFoo IFoo.Bar() { return Bar(); } //Why is this necessary?
}
为什么 IFoo Bar()
的隐式实现是必要的,即使 Foo
无需转换就可以转换为 IFoo
?
最佳答案
在这种情况下需要它,因为 C# 不支持接口(interface)的返回类型协变,所以你的函数
public Foo Bar()
{
//...
}
不满足IFoo
接口(interface),因为Bar
方法的返回类型不同。
由于您还想实现该接口(interface),您唯一的选择就是显式实现,因为您已经在类上定义了一个 Bar()
方法。
关于c# - 在 C# 中,为什么接口(interface)实现必须显式实现方法的另一个版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959920/