什么是实例从它的名字一个通用的最佳方法是什么?它的、实例、名字、方法

2023-09-03 06:01:53 作者:一无所有人还丑

假设我有一个通用的字符串中的MyCustomGenericCollection(的MyCustomObjectClass)的形式,只有类的名称,也不知道它来自于组装,什么是创建一个对象实例的最简单的方法?

Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object?

如果有帮助,我知道,这个类实现IMyCustomInterface,距离加载到当前的AppDomain的程序集。

If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.

马库斯·奥尔森给了一个很好的例子这里,但我看不出如何将其应用于泛型。

Markus Olsson gave an excellent example here, but I don't see how to apply it to generics.

推荐答案

在你分析它,使用的 Type.GetType(串)获得引用所涉及的类型,然后使用的 Type.MakeGenericType(键入[])构造您所需要​​的特定的泛型类型。然后,使用 Type.GetConstructor(键入[])得到的引用构造具体的泛型类型,最后调用 ConstructorInfo.Invoke 来获得对象的实例

Once you parse it up, use Type.GetType(string) to get a reference to the types involved, then use Type.MakeGenericType(Type[]) to construct the specific generic type you need. Then, use Type.GetConstructor(Type[]) to get a reference to a constructor for the specific generic type, and finally call ConstructorInfo.Invoke to get an instance of the object.

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