Get type from generic type fullname

后端 未结 3 1764
执念已碎
执念已碎 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:04

    The easiest way is to try "reverse engineering".

    When you call eg.

    typeof(List)
    

    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.

提交回复
热议问题