Get Type by Name

我怕爱的太早我们不能终老 提交于 2019-12-08 07:00:33

问题


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.



来源:https://stackoverflow.com/questions/20008503/get-type-by-name

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