如何在运行时在.NET中检测类的存在? [英] How to detect the existence of a class at runtime in .NET?

查看:97
本文介绍了如何在运行时在.NET中检测类的存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible in a .NET app (C#), to conditionally detect if a class is defined at runtime?

示例实现 - 基于配置选项的类对象?

Sample implementation - say you want to create a class object based on a configuration option?

推荐答案

我做了这样的事情,类从Config并实例化它。在这个例子中,我需要确保配置中指定的类继承自一个名为NinjectModule的类,但我认为你得到了想法。

I've done something like that, load a class from the Config and instantiate it. In this example, I needed to make sure the class specified in the config inherited from a class called NinjectModule, but I think you get the idea.

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

这篇关于如何在运行时在.NET中检测类的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆