从实例化字符串泛型类型 [英] Instantiate a generic type from string

查看:125
本文介绍了从实例化字符串泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含与特定类型的泛型类的名称的字符串:

I have a string containing the name of a generic class with specified type:

string s = "GenericRouteHandler<MemberHandler>";



我如何从实例化这个字符串的实例?我知道如何使用实例Type.GetType()一个具体的类,然后使用激活,但我不知道去哪里泛型类。

How do I instantiate an instance from this string? I know how to instantiate a concrete class using Type.GetType() and then use Activator but I am not sure where to go with a generic class.

推荐答案

像这样的typeof(GenericRouteHandler<>)MakeGenericType(typeof运算(MemberHandler));

当然,如果你没有,你必须使用类型 Type.GetType(字符串)来获得类型,而不是 typeof运算

Of course if you don't have the types you have to use Type.GetType(string) to get the type instead of typeof.

修改:那么你必须激活键入 Activator.CreateInstance()或调用构造器,如果知道签名 myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams); ;它可以更快,如果缓存中的consturctors它可以更快然后Activator.CreateInstance()

EDIT: Then you have to activate the type Activator.CreateInstance() or invoke a contructor if know the signature myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams); ; it can be faster if cache the consturctors it can be faster then Activator.CreateInstance()

MSDN

这篇关于从实例化字符串泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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