Type.GetType(“namespace.a.b.ClassName”) returns nu

2018-12-31 09:29发布

This code:

Type.GetType("namespace.a.b.ClassName")

returns null.

and I have in the usings:

using namespace.a.b;

Update:

The type exists, it's in a different class library, and i need to get it by string name.

标签: c# reflection
16条回答
闭嘴吧你
2楼-- · 2018-12-31 09:45

if your class is not in current assambly you must give qualifiedName and this code shows how to get qualifiedname of class

string qualifiedName = typeof(YourClass).AssemblyQualifiedName;

and then you can get type with qualifiedName

Type elementType = Type.GetType(qualifiedName);
查看更多
荒废的爱情
3楼-- · 2018-12-31 09:50

If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:

using System.Web.Compilation
...
BuildManager.GetType(typeName, false);
查看更多
刘海飞了
4楼-- · 2018-12-31 09:56

Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

If neither of those things are true, you'll need an assembly-qualified name.

查看更多
心情的温度
5楼-- · 2018-12-31 09:59

try using this method

 public static Type GetType(string typeName)
        {
            var type = Type.GetType(typeName);
            if (type != null) return type;
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                type = a.GetType(typeName);
                if (type != null)
                    return type;
            }
            return null ;
        }
查看更多
临风纵饮
6楼-- · 2018-12-31 10:00

For me, a "+" was the key! This is my class(it is a nested one) :

namespace PortalServices
{
public class PortalManagement : WebService
{
    public class Merchant
    {}
}
}

and this line of code worked:

Type type = Type.GetType("PortalServices.PortalManagement+Merchant");
查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 10:01

This solution above seems to be the best to me, but it didn't work for me, so I did it as follows:

AssemblyName assemblyName = AssemblyName.GetAssemblyName(HttpContext.Current.Server.MapPath("~\\Bin\\AnotherAssembly.dll"));
string typeAssemblyQualifiedName = string.Join(", ", "MyNamespace.MyType", assemblyName.FullName);

Type myType = Type.GetType(typeAssemblyQualifiedName);

The precondition is that you know the path of the assembly. In my case I know it because this is an assembly built from another internal project and its included in our project's bin folder.

In case it matters I am using Visual Studio 2013, my target .NET is 4.0. This is an ASP.NET project, so I am getting absolute path via HttpContext. However, absolute path is not a requirement as it seems from MSDN on AssemblyQualifiedNames

查看更多
登录 后发表回答