问题描述
我有一组类,每一个都是不同的战略做同样的工作。
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文件中配置全类型名BigCorp.SuperApp.ClassB'只类名称'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>
编辑:我改的名称的到的类的,以便更好地表示该属性的意义
I changed name to class to better denote the meaning of that attribute.
这篇关于创建一个对象只知道类的名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!