当对象包含列表时覆盖等于成员

时间:2012-10-30 03:16:03

标签: c# equality

我一直在使用resharper来生成我的平等成员,这对我的单元测试非常有帮助。

但是,当我的对象包含列表时,它似乎不能正常工作。

 public class FileandVersions
{

    public string fileName { get; set; }

    public string assetConfigurationType { get; set; }

    public List<Versions> Versions { get; set; }

    protected bool Equals(FileandVersions other)
    {
        return string.Equals(fileName, other.fileName) && string.Equals(assetConfigurationType, other.assetConfigurationType) && Equals(Versions, other.Versions);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((FileandVersions) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hashCode = (fileName != null ? fileName.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (assetConfigurationType != null ? assetConfigurationType.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (Versions != null ? Versions.GetHashCode() : 0);
            return hashCode;
        }
    }
}

这是版本对象的定义。

public class Versions
{

    public string versionNumber { get; set; }
    public DateTime acctivationTime { get; set; }
    public string URL { get; set; }

    protected bool Equals(Versions other)
    {
        return string.Equals(versionNumber, other.versionNumber) && acctivationTime.Equals(other.acctivationTime) && string.Equals(URL, other.URL);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Versions) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hashCode = (versionNumber != null ? versionNumber.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ acctivationTime.GetHashCode();
            hashCode = (hashCode*397) ^ (URL != null ? URL.GetHashCode() : 0);
            return hashCode;
        }
    }
}

即使对象是等效的,这些对象的比较也会失败。当对象包含列表时,编写相等成员的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您应该用以下代码替换等式表达式的Equals(Versions, other.Versions)

((Versions == null && other.Versions == null) || Versions != null && other.Versions != null && Versions.SequenceEqual(other.Versions))

此表达式在

时为真
  • Versions都是null
  • 两个Versions都不是null,并且它们包含相同顺序的相同元素