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);
}