确定要基于值创建哪个派生类?

时间:2018-08-16 11:11:58

标签: c# inheritance derived-class

我想知道这是否可行。我有许多类都是从相同的基类(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方法中的代码 variables

希望如此。

2 个答案:

答案 0 :(得分:2)

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();

答案 1 :(得分:0)

具有Config.ClassToUse返回派生类的类型,而不是标识它的整数。

然后您的代码可以缩短为:

private int ReturnInt(int x) { x = x + 1 return x; }