【问题标题】:Result type covariance - generic class with method returning both an interface type and a specific type [duplicate]结果类型协方差-具有返回接口类型和特定类型的方法的泛型类[重复]
【发布时间】:2023-03-04 23:30:01
【问题描述】:

我有这两个接口:

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

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

我想以这种方式在泛型类中实现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() 确实返回了一个实现IResult 的对象?我知道我可能会在此基础上引入 out T 协方差接口,但我无法摆脱它 - 为什么 T 类型限制不足以确保类型安全?

【问题讨论】:

  • 编译器没有理由不能完成函数覆盖的返回类型协方差,只是语言不支持这个(它可能不支持它,因为运行时不支持)不支持)。您可以看到此代码在其他语言中工作。
  • 他可以简单地使他的接口也通用,并让方法返回T。
  • @Mishka 或实际实现接口(即返回 IResult)。
  • “但问题是:为什么编译器不能弄清楚,T GetResult() 确实返回了一个实现 IResult 的对象?”签名根本不匹配。不考虑泛型,如果一个接口方法被声明为返回object,你是否期望能够用一个声明为返回string的方法来实现它?因为从来没有这样。

标签: c# generics interface covariance


【解决方案1】:

因为:

IResult GetResult(string someId);

不等于:

T GetResult(string id)

您告诉编译器 T 是任何实现 IResult 的类,而不是 IResult。这两件事不一样。

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多