2012-11-08 65 views

回答

1

您可以使用通用約束像這樣:

void set<TList, TElement>(TElement value, TList list) 
     where TList: IList<TElement>; 
1

(我會在我的答案前加一個參數和參數區別的提示:參數是某物的「佔位符」,參數是填充參數的值(因此t erm「參數參數」)。例如,類List<TFoo>具有名爲TFoo的參數,但實例List<String>對於參數TFoo具有參數String。)。

類型是「通用」或「具體」(即非通用)。

通用類型參數參數可以是任何類型,具體的或通用的。一個泛型類型,其所有參數都被具體類型參數填充,成爲具體的本身;所以List<String>是具體的,因爲String是具體的,但List<TFoo>不具體,因爲TFoo是一個類型參數。

因此,很容易發現泛型類可以以通用形式或以具體形式遞歸嵌套。當然,你可以只使用通用形式的泛型類或方法範圍內,例如以下是完全合法的:

private static IEnumerable<List<Dictionary<String,Int32>>> foo = new Collection<List<Dictionary<String,Int32>>>(); // this is completely concrete 

static void DoSomething<TBaz>(IEnumerable<List<Dictionary<TBaz,Int32>>> baz) { // this is generic because TBaz is not specified 

    List<TBaz> someList = new List<TBaz>(); // you can use the undefined TBaz because it's listed in the generic method's type arguments. 
} 

static void Main() { 
    DoSomething(foo); // the compiler will infer TBaz from the String argument used in the foo field 
} 
1

我想你想詢問是否可以做出具體Type aV .. 。

,如果這是你的問題,那麼,你必須定義方法如下所示:

void set<V>(V a, List<V> b) 

如果你意味着aType型的,然後是到0123的問題被允許作爲類型參數。你的例子不會編譯,但是,因爲aint而不是Type

相關問題