[英]Instantiate a generic type from string
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. 我知道如何使用Type.GetType()实例化一个具体的类,然后使用Activator,但我不知道在哪里使用泛型类。
Like this typeof(GenericRouteHandler<>).MakeGenericType(typeof(MemberHandler));
像这样的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
. 当然,如果您没有类型,则必须使用Type.GetType(string)
来获取类型而不是typeof
。
EDIT : Then you have to activate the type Activator.CreateInstance()
or invoke a contructor if know the signature myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams);
编辑 :然后你必须激活类型Activator.CreateInstance()
或调用一个构造myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams);
如果知道签名myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams);
; ; it can be faster if cache the consturctors it can be faster then Activator.CreateInstance() 如果缓存consturctors它可以更快,它可以比Activator.CreateInstance()更快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.