从名字中实例化一个泛型的最好方法是什么?

问题描述:

假设我只有泛型类名作为“MyCustomGenericCollection(MyCustomObjectClass)”形式的字符串,并且不知道它来自哪个程序集,创建该对象实例的最简单方法是什么?从名字中实例化一个泛型的最好方法是什么?

如果有帮助,我知道该类实现IMyCustomInterface并且来自加载到当前AppDomain中的程序集。

Markus Olsson举了一个很好的例子here,但我不明白如何将它应用到泛型。

解析完成后,请使用Type.GetType(string)来获取涉及的类型的引用,然后使用Type.MakeGenericType(Type[])构造所需的特定泛型类型。然后,使用Type.GetConstructor(Type[])获得对特定泛型的构造函数的引用,最后调用ConstructorInfo.Invoke来获取对象的实例。

Type t1 = Type.GetType("MyCustomGenericCollection"); 
Type t2 = Type.GetType("MyCustomObjectClass"); 
Type t3 = t1.MakeGenericType(new Type[] { t2 }); 
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes); 
object obj = ci.Invoke(null); 

如果你不介意的话翻译成VB.NET,这样的事情应该工作

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) 
{ 
    // find the type of the item 
    Type itemType = assembly.GetType("MyCustomObjectClass", false); 
    // if we didnt find it, go to the next assembly 
    if (itemType == null) 
    { 
     continue; 
    } 
    // Now create a generic type for the collection 
    Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);; 

    IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType); 
    break; 
} 

MSDN文章How to: Examine and Instantiate Generic Types with Reflection介绍了如何使用反射来创建一个通用类型的实例。与Marksus的样本一起使用应该有希望让你开始。