创建一个只知道类名的对象? [英] Create an object knowing only the class name?

查看:128
本文介绍了创建一个只知道类名的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组课程,每个课程都有不同的策略工作。

I have a set of classes, each one is a different strategy to do the same work.

namespace BigCorp.SuperApp
{
    public class BaseClass { }
    public class ClassA : BaseClass { }
    public class ClassB : BaseClass { }
}

其中使用的策略是可配置的。我想在app.config文件中仅配置类名称ClassB,而不是完整类型名称BigCorp.SuperApp.ClassB。

The choice of which strategy to use is configurable. I want to configure only the class name 'ClassB' instead of the full type name 'BigCorp.SuperApp.ClassB' in the app.config file.

<appConfig>
   <SuperAppConfig>
      <Handler name="ClassB" />
   </SuperAppConfig>
</appConfig>

但是,反射调用失败,因为他们需要完整的类型名称,特别是

However, the reflection calls fail because they expect the full type name, particularly

Type t = Type.GetType("ClassB"); // results in t == null
BaseClass c = Activator.CreateInstance(t) as BaseClass; // fails

如何在配置只有类名的同时工作?将命名空间连接到完整类型名称的类名称?是否有另一个反射调用工作?

How can I get this to work while configuring only the class name? Concatenate the namespace to the class name for full type name? Is there another reflection call that works?

如果你认为这是无用的,我应该期望配置包含完整的类型名称,我开放的解决方案!

If you think this is useless and I should expect the configuration to contain the full type name, I am open to that solution! Just provide rationale to convince me.

(我不会从这个程序集/命名空间之外加载类型)

(I will not be loading a type from outside this assembly/namespace)

推荐答案

由于你知道所有的类都来自同一个命名空间,所以配置一次并使用:

Since you know all classes will be coming from the same namespace, configure it once and use that:

<appConfig>
   <SuperAppConfig handlerNamespace="BigCorp.SuperApp">
      <Handler class="ClassB" />
   </SuperAppConfig>
</appConfig>

修改:我将名称更改为 class 以更好地表示该属性的含义。

I changed name to class to better denote the meaning of that attribute.

这篇关于创建一个只知道类名的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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