什么是实例从它的名字一个通用的最佳方法是什么? [英] What's the best way to instantiate a generic from its name?

查看:106
本文介绍了什么是实例从它的名字一个通用的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个通用的字符串中的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);

这篇关于什么是实例从它的名字一个通用的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆