Equals, GetHashCode, EqualityComparers and fuzzy equality

前端 未结 3 1665
离开以前
离开以前 2021-01-20 07:12

For an object with properties A, B, C, D, StartDate and EndDate if I wanted to implement something where any two objects are equal if they have identical A, B and C and over

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 07:42

    It is possible. The only rule for GetHashCode is that A.GetHashCode() must equal B.GetHashCode() if A == B. The opposite, if A == B A.GetHashCode() == B.GetHashCode() does not have to be true.

    So you can simply make GetHashCode like so

    public override int GetHashCode()
    {
        return A.GetHashCode() ^ B.GetHashCode() ^ C.GetHashCode();
    }
    

    GetHashCode is not for identity!! It is used for grouping 'similar' objects.

    Proof:

    string a = "a";
    string b = "EUKCnPMLpp";
    Console.WriteLine("a = '{0}', b = '{1}', Same = {2}", a, b, a == b);
    Console.WriteLine("a.GetHashCode() = {0}, b.GetHashCode() = {1}, Same = {2}", a.GetHashCode(), b.GetHashCode(), a.GetHashCode() == b.GetHashCode());
    

提交回复
热议问题