这段代码:

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

返回null。

我在使用:

using namespace.a.b;

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


当前回答

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

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

这行代码起作用了:

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

其他回答

Dictionary<string, Type> typeCache;
...
public static bool TryFindType(string typeName, out Type t) {
    lock (typeCache) {
        if (!typeCache.TryGetValue(typeName, out t)) {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
                t = a.GetType(typeName);
                if (t != null)
                    break;
            }
            typeCache[typeName] = t; // perhaps null
        }
    }
    return t != null;
}

我打开用户控件取决于用户有权访问数据库中指定的用户控件。所以我使用这个方法来获取TypeName…

Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))

所以现在可以使用strType中返回的值来创建该对象的实例。

非常晚的回复,但如果有人在十年后处理这个问题:

有一个非常非常小的机会,你的类在Visual Studio的构建动作设置为“内容”而不是“编译”。

在“解决方案资源管理器”中单击类,然后查看属性。

检查Build Action是“Compile”,而不是“Content”。

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

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

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

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

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