这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
当前回答
我打开用户控件取决于用户有权访问数据库中指定的用户控件。所以我使用这个方法来获取TypeName…
Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))
所以现在可以使用strType中返回的值来创建该对象的实例。
其他回答
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;
}
确保逗号直接位于完全限定名之后
typeof(namespace.a.b.ClassName, AssemblyName)
因为这不会起作用
typeof(namespace.a.b.ClassName ,AssemblyName)
在这件事上我被难住了好几天
type . gettype ("namespace.qualified.TypeName")仅在mscorlib.dll或当前正在执行的程序集中找到该类型时才有效。
如果这两种情况都不是真的,你将需要一个程序集限定的名称:
Type.GetType("namespace.qualified.TypeName, Assembly.Name")
如果程序集被引用并且Class可见:
typeof(namespace.a.b.ClassName)
GetType返回null,因为没有找到类型,使用typeof,编译器可以帮助你找出错误。
尝试使用包含程序集信息的完整类型名称,例如:
string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
Type myClassType = Type.GetType(typeName);
当我只使用名称空间时,也遇到了同样的情况。Classname来获取不同程序集中的类类型,这将不起作用。只有在如上所示的类型字符串中包含程序集信息时才有效。