【发布时间】:2020-08-19 08:32:41
【问题描述】:
我有很多对象,我想检查这些对象的列表是否相等。
我为每个对象定义了一个 EqualityComparer:
public class BaseAssociatedEntity : BasePage
{
protected IWebElement EntityElement;
protected virtual IWebElement EntityLink => EntityElement.FindElement(By.TagName("a"));
public string EntityName => EntityLink.Text;
public BaseAssociatedEntity(IWebElement entityElement, IWebDriver driver, string username, string password)
: base(driver, driver.Url, username, password, TimeoutInSecondsConstants.Three)
{
EntityElement = entityElement;
}
public bool Equals(BaseAssociatedEntity that)
{
return EntityName == that.EntityName;
}
}
public class BaseAssociatedEntityEqual : EqualityComparer<BaseAssociatedEntity>
{
public override bool Equals(BaseAssociatedEntity x, BaseAssociatedEntity y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null) return false;
return x.Equals(y);
}
public override int GetHashCode(BaseAssociatedEntity obj) => obj.GetHashCode();
}
然后我想调用以下方法来检查 BaseAssociatedEntity 类型的 2 个列表是否为 SequenceEqual():
protected bool BothNullOrEqual(List<BaseAssociatedEntity> left, List<BaseAssociatedEntity> right)
{
if (left == null && right == null) return true;
if (left != null && right != null) return left.SequenceEqual(right, new BaseAssociatedEntityEqual());
return false;
}
但我最终为我拥有的每个对象编写了这个 BothNullOrEqual 方法:
protected bool BothNullOrEqual(List<NotificationGroupAssociatedEntity> left,
List<NotificationGroupAssociatedEntity> right)
{
if (left == null && right == null) return true;
if (left != null && right != null) return left.SequenceEqual(right, new NotificationGroupAssociatedEntityEqual());
return false;
}
等等..如何使用我专门定义的 EqualityComparer 使这个方法通用,以便它适用于所有类型?
【问题讨论】:
标签: c# generics collections equality iequalitycomparer