ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 根据值确定要创建的派生类?

2019-07-01 11:56:12  阅读:208  来源: 互联网

标签: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方法中的代码因类的每个不同实例而异.

希望有道理.

解决方法:

这是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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有