从泛型类型全名获取类型(Get type from generic type fullname)

编程入门 行业动态 更新时间:2024-10-28 20:25:12
从泛型类型全名获取类型(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]]");

更多推荐

本文发布于:2023-07-15 11:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1112880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   全名   type   generic   fullname

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!