如何让MonthlyQuota类兼容EmployeeVacationForm与EmployeeVacationForm_Remote?
修改MonthlyQuota类以支持多种假期表单类型
问题背景
现有MonthlyQuota类仅支持EmployeeVacationForm类型,现在需要扩展支持EmployeeVacationForm_Remote类型,且保持原有的调用语法不变:
// 原支持的调用 var staffResults = vacations.Select(vf => new MonthlyQuota(vf)); // 需要新增支持的调用 var staffResults = vacations.Select(rvf => new MonthlyQuota(rvf));
推荐解决方案:抽象基类/接口统一处理
这种方式符合面向抽象编程原则,扩展性强,后续新增其他表单类型只需继承基类即可。
步骤1:定义公共基类/接口
首先为两种表单类定义一个包含公共属性的基类(或接口):
// 定义抽象基类,包含两种表单共有的属性和行为 public abstract class BaseEmployeeVacationForm { public DateTime? DateCreated { get; set; } public MonthlyQuota QuotaResult { get; set; } } // 让现有表单类继承基类 public class EmployeeVacationForm : BaseEmployeeVacationForm { // 原有业务逻辑代码 } // 远程表单类同样继承基类 public class EmployeeVacationForm_Remote : BaseEmployeeVacationForm { // 远程表单特有业务逻辑代码 }
步骤2:修改MonthlyQuota类
将Form属性改为基类类型,并添加对应构造函数:
public class MonthlyQuota { // 改为基类类型,兼容所有继承自BaseEmployeeVacationForm的子类 public virtual BaseEmployeeVacationForm Form { get; set; } // DateEmployeeSubmitted逻辑无需修改,因为基类已包含DateCreated属性 public virtual DateTime? DateEmployeeSubmitted => Form?.DateCreated; // 保留原有构造函数 public MonthlyQuota(QuarterlySupport document) { Document = document; } // 修改内部构造函数的参数类型为基类 internal MonthlyQuota(QuarterlySupport document, BaseEmployeeVacationForm form) : this(document) { Form = form; form.QuotaResult = this; } // 添加直接接受EmployeeVacationForm的公共构造函数,兼容原调用 public MonthlyQuota(EmployeeVacationForm form) : this(null, form) { } // 添加接受EmployeeVacationForm_Remote的公共构造函数,支持新调用 public MonthlyQuota(EmployeeVacationForm_Remote form) : this(null, form) { } // 补充原代码中缺失的Document属性定义 public QuarterlySupport Document { get; set; } }
备选方案:泛型实现
如果不需要统一抽象处理,也可以用泛型方式实现,适合临时扩展场景:
// 先定义约束接口,确保泛型类型包含必要属性 public interface IVacationForm { DateTime? DateCreated { get; set; } MonthlyQuota<IVacationForm> QuotaResult { get; set; } } // 让两种表单实现接口 public class EmployeeVacationForm : IVacationForm { public DateTime? DateCreated { get; set; } public MonthlyQuota<IVacationForm> QuotaResult { get; set; } // 原有业务代码 } public class EmployeeVacationForm_Remote : IVacationForm { public DateTime? DateCreated { get; set; } public MonthlyQuota<IVacationForm> QuotaResult { get; set; } // 远程表单特有代码 } // 修改为泛型类 public class MonthlyQuota<TForm> where TForm : IVacationForm { public virtual TForm Form { get; set; } public virtual DateTime? DateEmployeeSubmitted => Form?.DateCreated; public MonthlyQuota(QuarterlySupport document) { Document = document; } internal MonthlyQuota(QuarterlySupport document, TForm form) : this(document) { Form = form; form.QuotaResult = this as MonthlyQuota<IVacationForm>; } public MonthlyQuota(TForm form) : this(null, form) { } public QuarterlySupport Document { get; set; } }
调用时编译器会自动推断泛型类型:
var staffResults = vacations.Select(vf => new MonthlyQuota<EmployeeVacationForm>(vf)); var remoteStaffResults = remoteVacations.Select(rvf => new MonthlyQuota<EmployeeVacationForm_Remote>(rvf));
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

