如何在.NET中检测运行时类的存在?

是否有可能在.NET应用程序(C#)中有条件地检测是否在运行时定义了类?

示例实现 – 假设您要基于配置选项创建类对象?

我做过类似的事情 ,从Config加载一个类并实例化它。 在这个例子中,我需要确保配置中指定的类inheritance自一个名为NinjectModule的类,但我认为你明白了。

protected override IKernel CreateKernel() { // The name of the class, eg retrieved from a config string moduleName = "MyApp.MyAppTestNinjectModule"; // Type.GetType takes a string and tries to find a Type with // the *fully qualified name* - which includes the Namespace // and possibly also the Assembly if it's in another assembly Type moduleType = Type.GetType(moduleName); // If Type.GetType can't find the type, it returns Null NinjectModule module; if (moduleType != null) { // Activator.CreateInstance calls the parameterless constructor // of the given Type to create an instace. As this returns object // you need to cast it to the desired type, NinjectModule module = Activator.CreateInstance(moduleType) as NinjectModule; } else { // If the Type was not found, you need to handle that. You could instead // initialize Module through some default type, for example // module = new MyAppDefaultNinjectModule(); // or error out - whatever suits your needs throw new MyAppConfigException( string.Format("Could not find Type: '{0}'", moduleName), "injectModule"); } // As module is an instance of a NinjectModule (or derived) class, we // can use it to create Ninject's StandardKernel return new StandardKernel(module); } 
 string className="SomeClass"; Type type=Type.GetType(className); if(type!=null) { //class with the given name exists } 

关于你问题的第二部分: –

示例实现 – 假设您要基于配置选项创建类对象?

我不知道你为什么要这样做。 但是,如果您的类实现了一个接口,并且您希望根据配置文件动态创建这些类的对象,我认为您可以查看Unity IoC容器 。 它真的很酷,很容易使用如果它适合你的情况。 这里有一个如何做到这一点的例子。

Activator.CreateInstance可能适合账单:

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

当然,如果你不能实例化类,它会抛出exception,这与类“是否存在”不完全相同。 但是如果你不能实例化它并且你不打算只调用静态成员,它应该为你做的伎俩。

您可能正在寻找具有字符串参数的重载,第一个参数应该是程序集的名称,第二个参数是类的名称(完全命名空间限定)。