从名称实例化泛型的最佳方法是什么?
时间:2020-03-06 14:41:30 来源:igfitidea点击:
假设我只有通用类的类名,并且是字符串形式的" MyCustomGenericCollection(of MyCustomObjectClass)",并且不知道其来源,那么创建该对象实例的最简单方法是什么?
如果有帮助,我知道该类实现了IMyCustomInterface,并且来自于加载到当前AppDomain中的程序集。
马库斯·奥尔森(Markus Olsson)在这里给出了一个很好的例子,但是我不知道如何将其应用于泛型。
解决方案
解析完之后,请使用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文章"如何:使用反射检查和实例化通用类型"介绍了如何使用反射创建通用类型的实例。将其与Marksus的示例结合使用,有望使我们入门。