2
當我運行程序時彈出一條錯誤消息,它表示:對象引用未設置爲來自methodinfo.invoke(data,null)的對象實例。我想是在運行時創建一個動態的泛型集合,依賴於XML文件,也可以是list<classname>
,dictionary<string, classname>
,customgenericlist<T>
等通過反射動態創建通用列表時出錯
下面是代碼:使用列表作爲測試對象。
data = InstantiateGeneric("System.Collections.Generic.List`1", "System.String");
anobj = Type.GetType("System.Collections.Generic.List`1").MakeGenericType(Type.GetType("System.String"));
MethodInfo mymethodinfo = anobj.GetMethod("Count");
Console.WriteLine(mymethodinfo.Invoke(data, null));
這是實例上述數據類型的代碼:
public object InstantiateGeneric(string namespaceName_className, string generic_namespaceName_className)
{
Type genericType = Type.GetType(namespaceName_className);
Type[] typeArgs = {Type.GetType(generic_namespaceName_className)};
Type obj = genericType.MakeGenericType(typeArgs);
return Activator.CreateInstance(obj);
}