结果类型协方差 - 泛型 class 方法返回接口类型和特定类型

Result type covariance - generic class with method returning both an interface type and a specific type

我有这两个接口:

public interface IResult
{
    object SomeProperty {get;set;}
}

public interface IFooManager
{
    IResult GetResult(string someId);
}

我想以这种方式在通用 class 中实现 IFooManager

public class MyFooManager<T> : IFooManager where T: class, IResult
{
    public T GetResult(string id)
    {
        return null; //the value doesn't really matter here
    }
}

但是,这会导致编译错误:

Cannot implement method from interface [..].IFooManager. Return type should be [..].IResult

现在,我知道我可以通过另外显式定义接口方法来解决这个问题,如下所示:

IResult IFooManager.GetResult(string id)
{
    return GetResult(id);
}

但问题是:为什么编译器不能弄清楚 T GetResult() 确实 returns 一个实现 IResult 的对象?我知道我可能会在此基础上引入一个 out T 协方差接口,但我无法摆脱它 - 为什么 T 类型限制不足以确保类型安全?

因为:

IResult GetResult(string someId);

不等于:

T GetResult(string id)

您用约束告诉编译器 T 是实现 IResult 的任何 class - 而不是 IResult。这两件事是不一样的。