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))

この式は次の場合に当てはまります

  • 両方ともVersionsnullまたは
  • どちらもVersionsではなくnull、同じ要素が同じ順序で含まれています
于 2012-10-30T03:24:23.217 に答える