Ola*_*eni 5 c# reflection runtime class
是否有可能在.NET应用程序(C#)中有条件地检测是否在运行时定义了类?
示例实现 - 假设您要基于配置选项创建类对象?
string className="SomeClass";
Type type=Type.GetType(className);
if(type!=null)
{
//class with the given name exists
}
Run Code Online (Sandbox Code Playgroud)
对于您问题的第二部分:-
示例实现 - 假设您想根据配置选项创建一个类对象?
我不知道你为什么要这样做。但是,如果您的类实现了一个接口,并且您想根据配置文件动态创建这些类的对象,我认为您可以查看Unity IoC container。如果它适合您的场景,它真的很酷并且非常易于使用。关于如何做到这一点的一个例子是here。
我已经做了类似的事情,从配置加载一个类并实例化它。在此示例中,我需要确保配置中指定的类继承自名为 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8921 次 |
| 最近记录: |