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

发布于 2024-08-26 23:04:53 字数 79 浏览 5 评论 0 原文

是否可以在 .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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鹤仙姿 2024-09-02 23:04:53
string className="SomeClass";
Type type=Type.GetType(className);
if(type!=null)
{
//class with the given name exists
}

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

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

我不知道你为什么要这么做。但是,如果您的类实现了一个接口,并且您想根据配置文件动态创建这些类的对象,我认为您可以查看Unity IoC容器。如果它适合您的场景,它真的很酷并且非常易于使用。有关如何执行此操作的示例是 此处

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

For the second part of your question :-

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

I dont know why you want to do that. However, If your classes implement an interface and you want to dynamically create objects of those classes based on configuration files, I think you can look at Unity IoC container. Its really cool and very easy to use If it fits your scenario. An example on how to do that is here.

蓝咒 2024-09-02 23:04:53

我已经做了类似的事情,从配置加载一个类并实例化它。在此示例中,我需要确保配置中指定的类继承自名为 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);
}

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);
}
み零 2024-09-02 23:04:53

Activator.CreateInstance 可能符合要求:

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

当然,如果您无法实例化该类,它会抛出异常,而这并不完全是与该类是否“存在”相同。但是,如果您无法实例化它并且您不想只调用静态成员,那么它应该可以满足您的要求。

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

Activator.CreateInstance may fit the bill:

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

Of course, it throws an exception if you can't instantiate the class, which isn't exactly the same thing as whether the class "exists". But if you can't instantiate it and you aren't looking to just call static members, it should do the trick for you.

You're probably looking for the overload that has string parameters, the first argument should be the name of the assembly, the second being the name of the class (fully namespace-qualified).

呆橘 2024-09-02 23:04:53

我的静态函数版本:

/// <summary>
/// returns if the class exists in the current context
/// </summary>
/// <param name="className">Class Name</param>
/// <returns>class status</returns>
public static bool ClassExist(string className)
{
    Type type = Type.GetType(className);
    if (type != null)
    {
        return true;
    }
    return false;
}

My static function versión:

/// <summary>
/// returns if the class exists in the current context
/// </summary>
/// <param name="className">Class Name</param>
/// <returns>class status</returns>
public static bool ClassExist(string className)
{
    Type type = Type.GetType(className);
    if (type != null)
    {
        return true;
    }
    return false;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文