Instantiate a generic type from string

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 16:15:31

问题


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

string s = "GenericRouteHandler<MemberHandler>";

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.


回答1:


Like this typeof(GenericRouteHandler<>).MakeGenericType(typeof(MemberHandler));

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

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



来源:https://stackoverflow.com/questions/4609969/instantiate-a-generic-type-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!