这段代码:

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

返回null。

我在使用:

using namespace.a.b;

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


当前回答

我被骗了。由于我想要创建的类型(按名称)都在我控制的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.

其他回答

如果你的类不在当前程序集中,你必须给出qualifiedName,这段代码显示了如何获得类的qualifiedName

string qualifiedName = typeof(YourClass).AssemblyQualifiedName;

然后你可以用qualifiedName获取type

Type elementType = Type.GetType(qualifiedName);

试试这个方法。

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

上面的解决方案对我来说似乎是最好的,但对我来说并不管用,所以我这样做了:

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来看,绝对路径并不是必需的

对我来说,“+”是关键! 这是我的类(它是一个嵌套的):

namespace PortalServices
{
public class PortalManagement : WebService
{
    public class Merchant
    {}
}
}

这行代码起作用了:

Type type = Type.GetType("PortalServices.PortalManagement+Merchant");

我被骗了。由于我想要创建的类型(按名称)都在我控制的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.