这段代码:

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

返回null。

我在使用:

using namespace.a.b;

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


当前回答

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

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

其他回答

type . gettype ("namespace.qualified.TypeName")仅在mscorlib.dll或当前正在执行的程序集中找到该类型时才有效。

如果这两种情况都不是真的,你将需要一个程序集限定的名称:

Type.GetType("namespace.qualified.TypeName, Assembly.Name")

对我来说,“+”是关键! 这是我的类(它是一个嵌套的):

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

这行代码起作用了:

Type type = Type.GetType("PortalServices.PortalManagement+Merchant");

如果你的类不在当前程序集中,你必须给出qualifiedName,这段代码显示了如何获得类的qualifiedName

string qualifiedName = typeof(YourClass).AssemblyQualifiedName;

然后你可以用qualifiedName获取type

Type elementType = Type.GetType(qualifiedName);

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

typeof(namespace.a.b.ClassName)

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

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

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

因为这不会起作用

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

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