2014-01-16 30 views
0
Type valueType = Type.GetType("int"); 
object value = new List<valueType>(); 

第一行編好,但第二行沒有。如何使用System.Type變量調用泛型方法?

我如何創建一個泛型列表(或稱通用的方法)

object value = foo<valueType>(); 

通過只類型的字符串表示?我的最終目標實際上是取兩個字符串「int」和「5(作爲一個例子),並將5的值賦給對象[並最終到userSettings]。但是我有一個方法可以將」 5" 實際價值,如果我可以告訴通用的方法是int類型的基於字符串表示

T StringToValue<T>(string s) 
{ 
    return (T)Convert.ChangeType(s, typeof(T)); 
} 

更新:我的想法是創建一個通用的對象,並調用泛型方法將使用相同的方法,但我想我錯了,我該怎麼稱呼這個通用方法?

+0

我更新的問題基本上是這個問題的一個副本:http://stackoverflow.com/questions/1408120/how-to-call-generic-method-with-a-given-type-object – TruthOf42

回答

0

試試這個:

Type valueType = Type.GetType("System.Int32"); 
Type listType = typeof(List<>).MakeGenericType(valueType); 
IList list = (IList) Activator.CreateInstance(listType); 

// now use Reflection to find the Parse() method on the valueType. This will not be possible for all types 
string valueToAdd = "5"; 
MethodInfo parse = valueType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static); 
object value = parse.Invoke(null, new object[] { valueToAdd }); 

list.Add(value); 
+0

輸出列表仍然不會通用 – michalczukm

+0

最後一行不會編譯。 –

+0

@HenkHolterman:我希望現在修復錯誤(現在無法訪問VS) – David

0

我將分享傑弗裏裏希特的書CLR通過C#關於構建泛型類型的例子,這是不特定的問題,但將有助於引導你找到這樣做的適當方式,你想要什麼:

public static class Program { 
    public static void Main() { 
     // Get a reference to the generic type's type object 
     Type openType = typeof(Dictionary<,>); 
     // Close the generic type by using TKey=String, TValue=Int32 
     Type closedType = openType.MakeGenericType(typeof(String), typeof(Int32)); 
     // Construct an instance of the closed type 
     Object o = Activator.CreateInstance(closedType); 
     // Prove it worked 
     Console.WriteLine(o.GetType()); 
     } 
} 

將顯示:Dictionary`2 [System.String,System.Int32]

+0

你如何使用它? –

+0

@HenkHolterman你如何使用代碼?這是個問題嗎? –

+0

是的,您如何將數據添加到「對象o」? –

1

Type.GetType("int")返回null。這是無效的,因爲int只是C#語言中的一個關鍵字,它與System.Int32類型相同。它對.NET CLR沒有特別的意義,所以它在反射中不可用。你可能意思是typeof(int)或(或者它並不重要,因爲那只是一個例子)。

無論如何,一旦你有權利Type,這就是你如何得到你的名單。關鍵是MakeGenericType

Type valueType = typeof(int); 
object val = Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType)); 
Console.WriteLine(val.GetType() == typeof(List<int>)); // "True" - it worked!