2017-10-09 131 views
3

我有这2个接口:结果类型协方差 - 与方法返回输入接口类型和特定类型的泛型类

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类型限制不足以确保类型安全?

+1

编译器无法完成函数重写的返回类型协变,理由是没有理由,除了语言不支持这个(并且它可能不支持它,因为运行时不支持它) 。你可以看到这个代码在其他语言中工作。 – milleniumbug

+0

他可以简单地使他的接口是通用的,并有方法返回T. – Mishka

+1

[为什么不C#推断我的泛型?](https://stackoverflow.com/questions/8511066/why-doesnt-c-sharp -infer-my-generic-types) –

回答

3

因为:

IResult GetResult(string someId); 

是不一样的:

T GetResult(string id) 

你告诉与T是实现IResult任何一类的约束编译器 - 不IResult。这两件事情是不一样的。