2014-02-10 36 views
1

我有以下類別:如何實例化一個泛型類C#中的一個抽象的約束

public abstract class ThingBase { } 

public class ThingA : ThingBase { } 

而下面的泛型類:

public class ThingOwner<ThingType> where ThingType : ThingBase { } 

我想創建一個ThingOwner例如像如下:

ThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>(); 

有了這個代碼,我得到以下錯誤:「燦不會將類型'ThingOwner(ThingA)'隱式轉換爲'ThingOwner(ThingBase)''「

我不知道如何使它工作。我知道現在有很多關於泛型類和繼承的討論,但我嘗試了幾乎所有的東西,並且找不到適用於我的解決方案。

謝謝!

+0

的可能重複[不能隱式轉換派生類型它的基泛型類型(http://stackoverflow.com/questions/12324020/cannot-implicitly-convert-derived-type-to-its-base-generic-type ) – csteinmueller

回答

3

你應該利用covariance for generic types介紹了C#4.0。爲了這個工作,你需要使用一個接口而不是一個類:

public interface IThingOwner<out ThingType> where ThingType : ThingBase { } 

public class ThingOwner<ThingType> : IThingOwner<ThingType> 
    where ThingType : ThingBase 
{ 

} 


IThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>(); 
+0

你節省了我的一週!謝謝! –

1

只有接口支持協變性/逆變性。如果你需要的類,然後只有這些可以工作:

ThingOwner<ThingBase> thingOwner = new ThingOwner<ThingBase>(); 
ThingOwner<ThingA> thingOwner = new ThingOwner<ThingA>(); 
1

除了上面的答案一些解釋。雖然你的問題可以理解,但想一想:

說明你有一個派生類,它接受一個類型參數ClassA。在ThingOwner<ClassA>中,只允許添加一個從ClassA派生的類的實例。當您將其轉換爲ThingOwner<BaseClass>時,突然允許添加ClassB的實例,該實例也源自BaseClass。這會損害你的程序,實際上是錯誤的。這就是爲什麼他們首先發明瞭仿製藥。

相關問題