2012-06-08 23 views
0

我需要在運行時創建一個List<T>類型:我有一個字符串,表示列表中單個項目的類型(T)和一個對象數組。 我的問題是:我如何獲得List<T>一個複雜的類型在運行時

我希望我解釋自己:)

感謝

回答

1

首先,你確定你想這樣做這樣?聞起來像一個設計缺陷。

這裏是如何做到這一點的例子:

var stringType = Type.GetType("System.String"); 
var listType = typeof (List<>); 
var stringListType = listType.MakeGenericType(stringType); 
var list = Activator.CreateInstance(stringListType) as IList; 

list.Add("Foo"); 
list.Add("Bar"); 
list.Add("Baz"); 
1

您可以使用類似的東西:

Type itemType = Type.GetType("my type name as string"); 
Type listType = typeof(List<>).MakeGenericType(itemType); 
return (IList) Activator.CreateInstance(listType); 
+0

我已經嘗試過這一點,但我的問題是,如何我現在才填充大名單退貨嗎? – alfdev

+1

通過投射到IList,您可以使用添加,刪除等。 –

+0

好的,我錯過了IList在激活者之前施放的...... – alfdev