Run typical type from string

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

string s = "GenericRouteHandler<MemberHandler>";

How to create an instance from this line? I know how to instantiate a specific class using Type.GetType () and then use Activator, but I'm not sure where to go with the generic class.

+3
source share
1 answer

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

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

EDIT : then you need to activate the type Activator.CreateInstance()or call the constructor if you know the signature myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams);; it can be faster if cache constants can be faster than Activator.CreateInstance ()

msdn

+2
source

Source: https://habr.com/ru/post/1783749/


All Articles