从泛型类型全名获取类型(Get type from generic type fullname)
我想从泛型类型全名得到这样的类型:
var myType = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");但它似乎不适用于这样的泛型类型...
有什么好的方法来做到这一点?
I would like to get type from generic type fullname like that :
var myType = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");But it seems to not work with generics types like that...
What is the good method to do that ?
最满意答案
如果您未指定程序集限定名称,则Type.GetType仅适用于mscorlib类型。 在您的示例中,您仅为嵌入式类型参数定义了AQN。
// this returns null: var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"); // but this works: var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");如果您使用Assembly.GetType而不是Type.GetType ,则原始类型字符串将起作用:
var myAsm = typeof(MyGenericType<>).Assembly; var type = myAsm.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");If you don't specify the assembly qualified name, Type.GetType works only for mscorlib types. In your example you has defined the AQN only for the embedded type argument.
// this returns null: var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"); // but this works: var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");Your original type string will work though, if you use Assembly.GetType instead of Type.GetType:
var myAsm = typeof(MyGenericType<>).Assembly; var type = myAsm.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");更多推荐
发布评论