2017-10-09 137 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。這兩件事情是不一樣的。