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

前端 未结 5 931
谎友^
谎友^ 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:27

    If the assembly has been loaded in the current domain then the code below usually works:

    public static Type GetTypeEx(string fullTypeName)
    {
        return Type.GetType(fullTypeName) ??
               AppDomain.CurrentDomain.GetAssemblies()
                        .Select(a => a.GetType(fullTypeName))
                        .FirstOrDefault(t => t != null);
    }
    

    You can use it like so:

    Type t = GetTypeEx("System.Net.Sockets.SocketException");
    

提交回复
热议问题