Get type from generic type fullname

谁说胖子不能爱 提交于 2020-01-11 09:25:55

问题


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 ?


回答1:


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



回答2:


The easiest way is to try "reverse engineering".

When you call eg.

typeof(List<int>)

you get

System.Collections.Generic.List`1[System.Int32]

You can then use this as a template, so calling

Type.GetType("System.Collections.Generic.List`1[System.Int32]")

will give you proper type.

Number after ` is the number of generic arguments, which are then listed in []using comma as a separator.

EDIT: If you take a look at FullName of any type, you will see how to handle types while also specifying assembly. That will require wrapping the type in extra [], so the end result would be

Type.GetType("System.Collections.Generic.List`1[[System.Int32, mscorlib]], mscorlib")

Of course, you can specify also the version, culture and public key token, if you need that.




回答3:


Try this:

var myType = Type.GetType("MyProject.MyGenericType`1, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]");

Then use MakeGenericType():

var finalType = myType.MakeGenericType(Type.GetType("MyProject.MySimpleType"));

Alternatively, if the open generic type can be determined at compile type, you can simply use the typeof operator with <>:

var myType = typeof(MyProject.MyGenericType<>);
var finalType = myType.MakeGenericType(typeof(MyProject.MySimpleType));

See MSDN



来源:https://stackoverflow.com/questions/39505938/get-type-from-generic-type-fullname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!