给出以下代码:
public interface IFoo {}
public interface IBar
{
IFoo MyMethod();
}
public abstract class MyClass<T> : IBar where T : IFoo
{
public abstract T MyMethod();
}
为什么我收到错误
MyClass<T> does not implement interface member IBar.MyMethod(). MyClass<T>.MyMethod() cannot implement IBar.MyMethod() because it does not have the matching return type of IFoo.
?
我添加了约束
where T : IFoo
,所以我希望 T 和 IFoo 可以互换。
实现接口时需要使用指定的返回类型,仅返回从正确类型派生的对象是不够的。由于同样的原因,以下非通用代码也会失败:
public class MyFoo : IFoo { }
public class MyClass : IBar
{
public MyFoo MyMethod() => new ();
}
这不起作用的原因似乎很简单,因为语言设计者没有考虑到付出的努力值得。 这个答案应该解释更多并且在这个问题上相当权威。
解决方案是制作一个显式接口实现,将调用转发给抽象方法:
public abstract class MyClass<T> : IBar where T : IFoo
{
public abstract T MyMethod();
IFoo IBar.MyMethod() => MyMethod();
}