2

我一直在使用 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;
        }
    }
}

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

4

1 回答 1

1

你应该用这个替换Equals(Versions, other.Versions)等式表达式:

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

当这个表达式为真时

  • 两者Versions都是null, 或
  • 两者Versions都不是null,并且它们以相同的顺序包含相同的元素
于 2012-10-30T03:24:23.217 回答