Get type from generic type fullname

后端 未结 3 1732
执念已碎
执念已碎 2021-01-18 17:27

I would like to get type from generic type fullname like that :

var myType = Type.GetType(\"MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Ver         


        
3条回答
  •  臣服心动
    2021-01-18 18:01

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

提交回复
热议问题