Get type from generic type fullname

I would like to get the type from the full type fullname:

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

But it doesn't seem to work with these types of generics ...

What is a good way to do this?

+4
source share
3 answers

If you do not specify a qualified assembly name, Type.GetTypeit only works for types mscorlib. In your example, you defined AQN only for an argument of a built-in type.

// 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 source line will work if you use Assembly.GetTypeinstead 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]]");
+3
source

Try the following:

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

, , typeof <>:

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

. MSDN

+3

- " ".

, .

typeof(List<int>)

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

,

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

.

`- , [], .

EDIT: FullName , , , . [],

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

, , , .

+3

Source: https://habr.com/ru/post/1654671/


All Articles