这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
当前回答
尝试使用包含程序集信息的完整类型名称,例如:
string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
Type myClassType = Type.GetType(typeName);
当我只使用名称空间时,也遇到了同样的情况。Classname来获取不同程序集中的类类型,这将不起作用。只有在如上所示的类型字符串中包含程序集信息时才有效。
其他回答
如果你的类不在当前程序集中,你必须给出qualifiedName,这段代码显示了如何获得类的qualifiedName
string qualifiedName = typeof(YourClass).AssemblyQualifiedName;
然后你可以用qualifiedName获取type
Type elementType = Type.GetType(qualifiedName);
如果程序集是构建ASP的一部分。NET应用程序,你可以使用BuildManager类:
using System.Web.Compilation
...
BuildManager.GetType(typeName, false);
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;
}
我被骗了。由于我想要创建的类型(按名称)都在我控制的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 (String)需要的类型。你应该使用Assembly.CreateQualifiedName(String, String)。
string typeName = "MyNamespace.MyClass"; // Type.FullName
string assemblyName = "MyAssemblyName"; // MyAssembly.FullName or MyAssembly.GetName().Name
string assemblyQualifiedName = Assembly.CreateQualifiedName(assemblyName , typeName);
Type myClassType = Type.GetType(assemblyQualifiedName);
Version, Culture和PublicKeyToken对于assemblyName来说是不需要的,这就是为什么你可以使用MyAssembly.GetName(). name。
gettype (String):
如果类型是当前正在执行的 在Mscorlib.dll中,提供类型名就足够了 由其名称空间限定。