使用EqualityComparer <ilist <t >>覆盖Equals并获取GetHashCode并按List的元素进行比较

时间:2019-01-21 15:04:57

标签: c# gethashcode iequalitycomparer

我有以下类,其中Equals和GetHashCode重写由Visual Studio(2017)自动生成:

public class A
{
    public string Id { get; set; }
    public long? Total { get; set; }
    public IList<B> Bs { get; set; }

    public override bool Equals(object obj)
    {
        var a = obj as A;
        return a != null &&
               Id == a.Id &&
               EqualityComparer<long?>.Default.Equals(Total, a.Total) &&
               EqualityComparer<IList<B>>.Default.Equals(Bs, a.Bs);
    }

    public override int GetHashCode()
    {
        var hashCode = -1568924569;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Id);
        hashCode = hashCode * -1521134295 + EqualityComparer<long?>.Default.GetHashCode(Total);
        hashCode = hashCode * -1521134295 + EqualityComparer<IList<B>>.Default.GetHashCode(Bs);
        return hashCode;
    }
}

public class B
{
    public string Id { get; set; }
    public long? Total { get; set; }

    public override bool Equals(object obj)
    {
        var b = obj as B;
        return b != null &&
               Id == b.Id &&
               EqualityComparer<long?>.Default.Equals(Total, b.Total);
    }

    public override int GetHashCode()
    {
        var hashCode = 716770973;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Id);
        hashCode = hashCode * -1521134295 + EqualityComparer<long?>.Default.GetHashCode(Total);
        return hashCode;
    }
}

问题是,即使两个列表中的所有元素在B.Equals覆盖下均相等,Bs列表也将返回false。我假设这是由于EqualityComparer<IList<B>>.Default.Equals(Bs, a.Bs)正在比较列表的引用而不是列表中的元素。

我尝试将A.Equals方法更改为

public override bool Equals(object obj)
{
    var a = obj as A;
    return a != null &&
           Id == a.Id &&
           EqualityComparer<long?>.Default.Equals(Total, a.Total) &&
           ((Bs == null && model.Bs == null) || (Bs != null && model.Bs != null && Bs.SequenceEqual(model.Bs));
}

它可以工作,但是我不确定两件事:

  • 我应该更改GetHashCode中的任何内容吗?
  • 我可以用一种更具可读性和效率的方式做到吗?

谢谢!

0 个答案:

没有答案