Get Type by Name

2019-06-03 19:50发布

问题:

In my code I am trying to get a type by name. When I was using a string argument I failed. Then I have tried to do the follwing in the Quick watch window:

Type.GetType(typeof(System.ServiceModel.NetNamedPipeBinding).Name)

returns null. Why? and how to get the desired type by name?

回答1:

Type.GetType can only find types in mscorlib or current assembly when you pass namespace qualified name. To make it work you need "AssemblyQualifiedName".

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Referece Type.GetType

System.ServiceModel.NetNamedPipeBinding lives in "System.ServiceModel.dll" hence Type.GetType can't find it.

This will work

Type.GetType(typeof(System.ServiceModel.NetNamedPipeBinding).AssemblyQualifiedName)

Or if you know the assembly already use following code

assemblyOfThatType.GetType(fullName);//This just need namespace.TypeName


回答2:

If you want use simple name (not AssemblyQualifiedName), and don't worry about ambiguous, you can try something like this:

    public static Type ByName(string name)
    {
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Reverse())
        {
            var tt = assembly.GetType(name);
            if (tt != null)
            {
                return tt;
            }
        }

        return null;
    }

Reverse() - for load most recently loaded type (for example after compilation of code from aspx)



回答3:

.Name gives you NetNamedPipeBinding, for GetType to work you'll need full assembly name (AssemblyQualifiedName)



回答4:

The other answers almost have it right. To load a type by name, you either need it's full name (if the assembly has already been loaded into the appdomain) or its Assembly Qualified name.

The full name is the type's name, including the namespace. You can get that by calling Type.GetType(typeof(System.ServiceModel.NetNamedPipeBinding).FullName). In your contrived example, this will work (since NetNamedPipeBinding's assembly is assured to be loaded).

If you can't be sure it's loaded, use Sriram's answer, and pass a full assembly qualified name (TopNamespace.SubNameSpace.ContainingClass, MyAssembly). This will have .NET try to find and load htat assembly, then get the type.