通过反射动态创建泛型列表时出错

本文关键字:列表 出错 泛型 创建 反射 动态 | 更新日期: 2023-09-27 18:13:56

当我运行程序时,弹出一个错误消息,它说:对象引用未设置为来自methodinfo的对象的实例。调用(数据,null)。我想要的是在运行时创建一个动态的通用集合,取决于xml文件,它可以是list<classname>, dictionary<string, classname>, customgenericlist<T>等。

下面是代码:使用list作为测试对象。

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

通过反射动态创建泛型列表时出错

Count是一个属性,而不是一个方法:

var prop = anobj.GetProperty("Count");
Console.WriteLine(prop.GetValue(data, null));

但是,最好转换为非泛型IList:

var data = (IList)InstantiateGeneric("System.Collections.Generic.List`1",
                                     "System.String");
Console.WriteLine(data.Count);

我还建议使用Type,而不是魔法字符串:

var itemType = typeof(string); // from somewhere, perhaps external
var listType = typeof(List<>).MakeGenericType(itemType);
var data = (IList)Activator.CreateInstance(listType);
Console.WriteLine(data.Count);