开发者

Instantiate a generic type from string

开发者 https://www.devze.com 2023-02-02 11:30 出处:网络
I have a str开发者_如何学运维ing containing the name of a generic class with specified type: string s = \"GenericRouteHandler<MemberHandler>\";

I have a str开发者_如何学运维ing 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消