这段代码:

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

返回null。

我在使用:

using namespace.a.b;

类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。


当前回答

如果程序集是构建ASP的一部分。NET应用程序,你可以使用BuildManager类:

using System.Web.Compilation
...
BuildManager.GetType(typeName, false);

其他回答

尝试使用包含程序集信息的完整类型名称,例如:

string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
Type myClassType = Type.GetType(typeName);

当我只使用名称空间时,也遇到了同样的情况。Classname来获取不同程序集中的类类型,这将不起作用。只有在如上所示的类型字符串中包含程序集信息时才有效。

试试这个方法。

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;
}

上面的解决方案对我来说似乎是最好的,但对我来说并不管用,所以我这样做了:

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

Type myType = Type.GetType(typeAssemblyQualifiedName);

前提条件是您知道程序集的路径。在我的情况下,我知道它,因为这是从另一个内部项目构建的程序集,它包含在我们的项目的bin文件夹中。

如果有问题的话,我使用的是Visual Studio 2013,我的目标是。net 4.0。这是一个ASP。NET项目,所以我得到绝对路径通过HttpContext。然而,从MSDN上的AssemblyQualifiedNames来看,绝对路径并不是必需的

确保逗号直接位于完全限定名之后

typeof(namespace.a.b.ClassName, AssemblyName)

因为这不会起作用

typeof(namespace.a.b.ClassName ,AssemblyName)

在这件事上我被难住了好几天

如果程序集被引用并且Class可见:

typeof(namespace.a.b.ClassName)

GetType返回null,因为没有找到类型,使用typeof,编译器可以帮助你找出错误。