[英]How do I use System.Type variable to call a generic method?
Type valueType = Type.GetType("int");
object value = new List<valueType>();
第一行編譯良好,但第二行則沒有。
如何創建通用列表(或調用通用方法)
object value = foo<valueType>();
通過僅具有類型的字符串表示形式?
我的最終目標實際上是采用兩個字符串“ int”和“ 5(作為示例)”,然后將5的值分配給對象[並最終分配給userSettings。]但是我有一種方法可以將“ 5”轉換為如果我可以告訴通用方法它是基於字符串表示形式的int類型,則為實際值。
T StringToValue<T>(string s)
{
return (T)Convert.ChangeType(s, typeof(T));
}
更新:我以為創建通用對象並調用通用方法將使用相同的方法,但是我想我錯了。 如何調用通用方法?
Type.GetType("int")
返回null
。 這是無效的,因為int
只是C#語言中的一個關鍵字,它等效於System.Int32類型。 它對.NET CLR沒有特殊含義,因此在反射中不可用。 您可能已經打算使用typeof(int)
或Type.GetType("System.Int32")
(或者這並不重要,因為那只是示例)。
無論如何,一旦您擁有正確的Type
,便可以通過這種方式獲取列表。 關鍵是MakeGenericType
。
Type valueType = typeof(int);
object val = Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));
Console.WriteLine(val.GetType() == typeof(List<int>)); // "True" - it worked!
嘗試這個:
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);
我將分享傑弗里·里希特(Jeffrey Richter)的《 CLR Via 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.