2015-10-20 55 views
2

我在我的類中有一個泛型類型參數。爲什麼我可以這樣做:通用左側接口參數

BaseFoo<InterfaceImplementation> foo = new ChildFoo<InterfaceImplementation>(); 

但不是這樣?編譯器不應該能夠找出AnInterfaceInterfaceImplementation的執行嗎?

BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>(); 

我希望能夠做這樣的事情:

BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>(); 
BaseFoo<AnInterface> bar = new ChildFoo<AnotherInterfaceImplementation>(); 

如果雙方實現都有一個共同的接口。

+3

將'BaseFoo'轉換爲接口並使用[Co-和Contravariance](https://msdn.microsoft.com/zh-cn/library/ee207183.aspx)。 –

+1

'桔子是一種水果,但你不能把一籃桔子當成一籃水果,因爲你可以把一根香蕉加入籃子',但不知何故,我總是得到這個比喻錯誤。 – Maarten

回答

1

的事實,即

class A {} 
class B : A {} 

並不意味着,這

class C<B> : C<A> {} 

你需要變化,但在C#中僅數據接口和委託。
你可以聲明變種接口,並從合作和逆變選擇:

IBaseFoo<out T> {} // this is covariant interface 
IBaseFoo<in T> {} // this is contravariant interface 

查看更多here