从泛型类型全名中获取类型 [英] Get type from generic type fullname

查看:66
本文介绍了从泛型类型全名中获取类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从这样的泛型类型全名中获取类型:

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.

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");

如果您使用 Assembly.GetType 而不是 Type.GetType,您的原始类型字符串将起作用:

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]]");

这篇关于从泛型类型全名中获取类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆