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

编程入门 行业动态 更新时间:2024-10-26 00:25:55
本文介绍了如何在运行时在.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中检测类的存在?

本文发布于:2023-11-06 03:59:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!