如何合并重复校验方法以减少冗余代码并提升可读性?
合并重复的C#列表校验方法
问题背景
现有以下逻辑完全重复的C#校验方法,均用于判断列表非空、列表元素数量大于0且首个元素的Person属性非空,希望通过合并方法减少冗余代码,提升可读性:
private bool IsValidPhoneAnnuitent(List<PhoneAnnuitant> annuitant) { if (annuitant is not null && annuitant.Count() > 0 && annuitant[0].Person is not null) return true; return false; } private bool IsValidAddressAnnuitent(List<AddressAnnuitant>? annuitant) { if (annuitant is not null && annuitant.Count() > 0 && annuitant[0].Person is not null) return true; return false; } private bool IsValidAnnuitent(List<Annuitant>? annuitant) { if (annuitant is not null && annuitant.Count() > 0 && annuitant[0].Person is not null) return true; return false; } private bool IsValidPhoneInsured(List<PhoneInsured>? insured) { if (insured is not null && insured.Count() > 0 && insured[0].Person is not null) return true; return false; }
解决方案
可以通过泛型实现代码复用,以下是两种可行方案:
方案1:泛型+委托(无需修改现有类)
通过委托传递获取Person属性的逻辑,无需改动原有实体类,适合快速改造:
// 通用校验方法 private bool IsValidListWithPerson<T>(List<T>? list, Func<T, object?> getPerson) { // 简化逻辑:直接返回布尔表达式结果,无需冗余if-else return list is not null && list.Count > 0 && getPerson(list[0]) is not null; }
使用示例
替换原有各校验方法的调用:
// 替代IsValidPhoneAnnuitent bool phoneAnnuitantValid = IsValidListWithPerson(phoneAnnuitantList, item => item.Person); // 替代IsValidAddressAnnuitent bool addressAnnuitantValid = IsValidListWithPerson(addressAnnuitantList, item => item.Person); // 替代IsValidAnnuitent bool annuitantValid = IsValidListWithPerson(annuitantList, item => item.Person); // 替代IsValidPhoneInsured bool phoneInsuredValid = IsValidListWithPerson(phoneInsuredList, item => item.Person);
方案2:泛型+接口(规范类型约束,适合长期维护)
定义统一接口约束所有包含Person属性的类,代码更规范、类型更安全:
步骤1:定义接口
public interface IPersonContainer { // 可根据实际Person类型调整(比如是具体类就替换为对应类型) object? Person { get; } }
步骤2:让实体类实现接口
让PhoneAnnuitant、AddressAnnuitant、Annuitant、PhoneInsured都实现该接口:
public class PhoneAnnuitant : IPersonContainer { public object? Person { get; set; } // 保留原有其他属性和方法 } // 其他实体类同理实现IPersonContainer接口
步骤3:编写通用校验方法
private bool IsValidListWithPerson<T>(List<T>? list) where T : IPersonContainer { return list is not null && list.Count > 0 && list[0].Person is not null; }
使用示例
调用时无需额外传递委托,代码更简洁:
bool phoneAnnuitantValid = IsValidListWithPerson(phoneAnnuitantList); bool addressAnnuitantValid = IsValidListWithPerson(addressAnnuitantList); bool annuitantValid = IsValidListWithPerson(annuitantList); bool phoneInsuredValid = IsValidListWithPerson(phoneInsuredList);
方案对比
- 方案1:无需修改现有代码,灵活快捷,适合临时复用场景。
- 方案2:通过接口规范类型,代码可读性和可维护性更强,适合长期迭代的项目。
内容的提问来源于stack exchange,提问作者jansy
相关产品推荐
相关产品推荐

