这段代码:

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

返回null。

我在使用:

using namespace.a.b;

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


当前回答

试试这个方法。

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

其他回答

我被骗了。由于我想要创建的类型(按名称)都在我控制的dll中,所以我只是在程序集中的dll中放置了一个静态方法,该方法采用简单的名称,并调用type。GetType从那个上下文返回结果。

The original purpose was so that the type could be specified by name in configuration data. I've since change the code so that the user specified a format to process. The format handler classes implement a interface that determines if the type can parse the specified format. I then use reflection to find types that implement the interface, and find one that handles the format. So now the configuration specifies a format name, a not a specific type. The reflection code can look at adjacent dlls and load, them so I have a sort poor man's plug-in architecture.

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

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

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

如果它是一个嵌套类型,您可能会忘记转换。到a +

不管怎样,typeof(T).FullName会告诉你应该说什么

编辑:顺便说一句,这些用法(我相信你知道)只是编译时对编译器的指令,因此不会对API调用的成功产生任何影响。(如果你有项目或装配的参考资料,可能会有潜在的影响-因此信息不是无用的,只是需要一些过滤…)

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

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

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

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

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