【问题标题】:Error when dynamically creating a generic list through reflection通过反射动态创建通用列表时出错
【发布时间】:2013-05-11 01:52:57
【问题描述】:

当我运行程序时会弹出一条错误消息,它说:对象引用未设置为来自 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);
        }

【问题讨论】:

    标签: c# vb.net reflection gettype


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-06-19
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2022-12-07
      相关资源
      最近更新 更多