如何编写通用方法,适配各类型自定义EqualityComparer比较列表?
通用化
BothNullOrEqual方法,适配自定义EqualityComparer 你现在这种重复写方法的情况确实挺冗余的,完全可以用泛型把这个方法统一成一个通用版本,不用再为每个实体类型复制粘贴代码了。下面给你两种实用的实现思路:
1. 基础泛型版本(手动传入比较器)
直接把方法改成泛型,让它接收对应类型的IEqualityComparer<T>作为参数,这样就能适配所有你定义了比较器的实体类型:
protected bool BothNullOrEqual<T>(List<T> left, List<T> right, IEqualityComparer<T> comparer) { if (left == null && right == null) return true; if (left != null && right != null) return left.SequenceEqual(right, comparer); return false; }
调用示例
之后检查不同类型的列表时,只需要传入对应的比较器实例就行:
// 检查BaseAssociatedEntity列表 bool baseEntitiesEqual = BothNullOrEqual(baseList1, baseList2, new BaseAssociatedEntityEqual()); // 检查NotificationGroupAssociatedEntity列表 bool notificationEntitiesEqual = BothNullOrEqual(notificationList1, notificationList2, new NotificationGroupAssociatedEntityEqual());
2. 进阶优化(自动创建比较器)
如果你的所有EqualityComparer都是无参构造的,还可以给泛型方法加约束,让它自动创建比较器实例,省得每次调用都手动new:
protected bool BothNullOrEqual<T, TComparer>(List<T> left, List<T> right) where TComparer : IEqualityComparer<T>, new() { if (left == null && right == null) return true; if (left != null && right != null) { var comparer = new TComparer(); return left.SequenceEqual(right, comparer); } return false; }
调用示例
这种情况下调用更简洁,只需要指定泛型参数即可:
bool baseEntitiesEqual = BothNullOrEqual<BaseAssociatedEntity, BaseAssociatedEntityEqual>(baseList1, baseList2); bool notificationEntitiesEqual = BothNullOrEqual<NotificationGroupAssociatedEntity, NotificationGroupAssociatedEntityEqual>(notificationList1, notificationList2);
额外小建议
另外,你现有的BaseAssociatedEntityEqual里的GetHashCode实现存在隐患——直接返回obj.GetHashCode()的话,如果实体类没有重写GetHashCode,会用默认的引用哈希码,这可能导致EqualityComparer工作异常。建议在实体类里重写GetHashCode:
public class BaseAssociatedEntity : BasePage { // ... 现有代码 ... public override int GetHashCode() { return EntityName?.GetHashCode() ?? 0; } }
这样比较器里的GetHashCode就能安全复用实体类的实现了。
内容的提问来源于stack exchange,提问作者Hdot
相关产品推荐
相关产品推荐

