这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
当前回答
非常晚的回复,但如果有人在十年后处理这个问题:
有一个非常非常小的机会,你的类在Visual Studio的构建动作设置为“内容”而不是“编译”。
在“解决方案资源管理器”中单击类,然后查看属性。
检查Build Action是“Compile”,而不是“Content”。
其他回答
当我只有类名时,我使用这个:
Type obj = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => String.Equals(t.Name, _viewModelName, StringComparison.Ordinal)).First();
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;
}
type . gettype ("namespace.qualified.TypeName")仅在mscorlib.dll或当前正在执行的程序集中找到该类型时才有效。
如果这两种情况都不是真的,你将需要一个程序集限定的名称:
Type.GetType("namespace.qualified.TypeName, Assembly.Name")
如果你的类不在当前程序集中,你必须给出qualifiedName,这段代码显示了如何获得类的qualifiedName
string qualifiedName = typeof(YourClass).AssemblyQualifiedName;
然后你可以用qualifiedName获取type
Type elementType = Type.GetType(qualifiedName);
上面的解决方案对我来说似乎是最好的,但对我来说并不管用,所以我这样做了:
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来看,绝对路径并不是必需的