2014-07-24 32 views
0

我有一個通用類,我想創建一個通用列表,其中底層類實現相同的接口。但是,並不是所有的實現給定的接口。在C#中創建通用對象的通用列表

一個例子比說明問題要容易。

internal interface ISomething 
{ 

} 

internal class ThisThing : ISomething 
{ 
} 

internal class ThatThing : ISomething 
{ 

} 

internal class SomethingElse 
{ 

} 

internal class GenericThing<T> 
{ 

} 

internal class DoThings 
{ 
    void Main() 
    { 
     var thing1 = new GenericThing<ThisThing>(); 
     var thing2 = new GenericThing<ThatThing>(); 

     var thing3 = new GenericThing<SomethingElse>(); 

     **var thingList = new List<GenericThing<ISomething>>() {thing1, thing2};** 
    } 

}

我無法創建thingList。有沒有辦法將實現相同接口的兩個東西轉換爲泛型集合,同時仍然保持GenericThing類不受接口約束。

+7

那麼,你的問題到底是什麼? –

+0

你想添加'thing3'到'List'嗎? – barrick

+3

'GenericThing'對於泛型參數不是協變的,所以這是行不通的。 – Servy

回答

4

如果使用covariant interface這是可能的:

internal interface IGenericThing<out T> 
{ 
} 

internal class GenericThing<T> : IGenericThing<T> 
{ 
} 

void Main() 
{ 
    var thing1 = new GenericThing<ThisThing>(); 
    var thing2 = new GenericThing<ThatThing>(); 

    var thing3 = new GenericThing<SomethingElse>(); 

    var thingList = new List<IGenericThing<ISomething>>() {thing1, thing2}; 
} 

注意,這僅僅是可能的,如果T僅在IGenericThing<T>用作輸出,從來沒有作爲輸入! (在我的例子中,它是未使用的,也是允許的;雖然顯然沒用)

+0

這就是我正在尋找的。謝謝。 – JNappi