2010-03-27 142 views
4

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

示例实现 - 说你想创建一个基于配置选项的类对象?

+0

Type.GetType(“someType”)有什么问题? – 2010-03-27 05:20:34

回答

2

I've done something like that,从Config中加载一个类并实例化它。在这个例子中,我需要确保配置中指定的类继承自名为NinjectModule的类,但我认为你明白了。

protected override IKernel CreateKernel() 
{ 
    // The name of the class, e.g. 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); 
} 
0

Activator.CreateInstance可以适应该法案:

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

当然,它抛出一个异常,如果你不能实例类,这是不完全一样的东西是否类“存在”。但是如果你不能实例化它,并且你不想调用静态成员,它应该为你做窍门。

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

+0

MSDN声明Actiator.CreateInstance()是“昂贵的函数”之一 - http://msdn.microsoft.com/en-us/magazine/cc163759.aspx。 此外,我不知道为什么你会想抛出一个异常,因为抛出异常也可能是昂贵的? – 2010-03-27 05:44:26

+1

“昂贵”是相对的。如果你只有几次这样做,它并不昂贵。如果你做了数百万次,你会想找到一个更好的解决方案。 – Gabe 2010-03-27 06:17:56

3
string className="SomeClass"; 
Type type=Type.GetType(className); 
if(type!=null) 
{ 
//class with the given name exists 
} 

对于你的问题的第二部分: -

样品实施 - 说你要 来创建基于 配置选项一个类的对象?

我不知道你为什么想这样做。但是,如果你的类实现了一个接口,并且你想根据配置文件动态创建这些类的对象,我想你可以看看Unity IoC容器。它非常酷,非常易于使用如果它适合你的场景。如何做到这一点的例子是here

+0

@Ashish:从配置创建实例是Unity所做的一件事。 – 2010-03-27 06:07:47

+0

@约翰,对。我知道它主要用于依赖注入。我只是建议他只是看看它。可能不是问题的答案。不管怎么说,还是要谢谢你。 – 2010-03-27 07:17:08

相关问题