c# – 根据值确定要创建的派生类?
作者:互联网
我想知道这是否可能.我有许多类都是从相同的基类(BaseClass)派生的.当我创建一个实例时,我需要根据配置值决定我需要创建哪个派生类.目前我正在做下面的事情,但我希望有一个更简洁的方法来实现这一点,如果我需要添加一个新的派生类,需要更少的维护.
BaseClass myclass;
switch (Config.ClassToUse)
{
case 1:
myclass= new DerivedClass1(Config);
break;
case 2:
myclass= new DerivedClass2(Config);
break;
case 3:
myclass = new DerivedClass3(Config);
break;
}
myclass.DoWork();
DoWork方法中的代码因类的每个不同实例而异.
希望有道理.
解决方法:
这是Config,知道要创建哪个类,这就是为什么让我们Config完成它的工作.我们应该摆脱神奇的数字(2代表什么?)并返回Type,而不是int.
快速补丁是
public class Config {
...
// Get rid of this, move logic into TypeToUse
public int ClassToUse {get { ... }}
public Type TypeToUse {
get {
string name = $"DerivedClass{ClassToUse}";
// Here we scan all types in order to find out the best one. Class must be
// 1. Derived from BaseClass
// 2. Not Abstract (we want to create an instance)
// Among these classes we find the required by its name DerivedClass[1..3]
// (as a patch). You should implement a more elaborated filter
// If we have several candidates we'll take the 1st one
return AppDomain
.CurrentDomain
.GetAssemblies() // scan all assemblies
.SelectMany(asm => asm
.GetTypes() // and all types
.Where(tp => typeof(BaseClass).IsAssignableFrom(tp))) // ... for derived classes
.Where(tp => !tp.IsAbstract) //TODO: Add more filters if required
.Where(tp => tp.Name.Equals(name)) //TODO: put relevant filter here
.FirstOrDefault();
}
}
public BaseClass CreateInstance() {
Type tp = TypeToUse;
if (tp == null)
return null; // Or throw exception
return Activator.CreateInstance(tp, this) as BaseType;
}
}
然后你可以把
BaseClass myclass = Config.CreateInstance();
myclass.DoWork();
标签:c,inheritance,derived-class 来源: https://codeday.me/bug/20190701/1346538.html