2013-05-16 47 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);