Get Type by Name

大憨熊 提交于 2019-12-08 01:24:26

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

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)

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!