Instantiate a generic type from string
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
精彩评论