How Type.GetType works when given partially qualified type name?

前端 未结 5 936
谎友^
谎友^ 2020-11-30 13:50

In numerous places do I encounter partially qualified type names of the form FullTypeName, AssemblyName, i.e. like Type.AssemblyQualifiedName only

5条回答
  •  青春惊慌失措
    2020-11-30 14:17

    True, Type.GetType(string) does require an AssemblyQualifiedName. This can be in many forms:

    MyNS.MyType, MyAssembly, Version=x.x.x.x, Culture=xxx, PublicKeyToken=XXXXXXXXXX
    

    The following are also valid AssemblyQualifiedNames:

    MyNS.MyType, MyAssembly, Version=x.x, Culture=xxx, PublicKeyToken=XXXXXXXXXX
    MyNS.MyType, MyAssembly, Culture=xxx, PublicKeyToken=XXXXXXXXXX
    MyNS.MyType, MyAssembly, PublicKeyToken=XXXXXXXXXX
    MyNS.MyType, MyAssembly
    

    For a signed assembly, the minimum required for a FullyQualifiedAssemblyName is:

    MyNS.MyType, MyAssembly, PublicKeyToken=XXXXXXXXXX
    

    For an unsigned assembly, the minimum required for a FullyQualifiedAssemblyName is:

    MyNS.MyType, MyAssembly
    

    No need for all the "hand waving" going on in the code snippets others have provided. Ensure that your type names are set up properly and you can access your types (and load assemblies dynamically) with a high degree of flexibility. I do this regularly.

    In OP's example using:

    Type.GetType("System.Net.Sockets.SocketException, System")
    

    The reason for the failure was the absence of the PublicKeyToken. The .Net FW assemblies are all signed and therefore require the PublicKeyToken to resolve the Assembly name. The following would work:

    Type.GetType("System.Net.Sockets.SocketException, System, PublicKeyToken=b77a5c561934e089")
    

提交回复
热议问题