这段代码:

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中返回的值来创建该对象的实例。

其他回答

确保逗号直接位于完全限定名之后

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")

你也可以得到不带程序集限定名但带有dll名的类型,例如:

Type myClassType = Type.GetType("TypeName,DllName");

我也遇到过同样的情况,这招对我很管用。我需要一个DataModel类型的对象。QueueObject”,并有一个引用“DataModel”,所以我得到的类型如下:

Type type = Type.GetType("DataModel.QueueObject,DataModel");

逗号后的第二个字符串是引用名称(dll名称)。

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.