为什么接口方法的实现不能返回应用了正确约束的泛型参数类型? (C#)

问题描述 投票:0回答:1

给出以下代码:

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 可以互换。

c# oop generics interface
1个回答
0
投票

实现接口时需要使用指定的返回类型,仅返回从正确类型派生的对象是不够的。由于同样的原因,以下非通用代码也会失败:

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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.