2013-05-16 104 views
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); 
     } 

回答

2

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