Equals, GetHashCode, EqualityComparers and fuzzy equality

与世无争的帅哥 提交于 2019-12-02 00:05:33

This is not possible.

Equality in .Net must be transitive, meaning that if a == b and b == c, then a == c.

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

If you are using the items in a hashtable then their GetHashCode method will be used initially to test for equality and if their hashes are found to be equal a call to their Equals method will be made to establish whether they are equal.

From the documentation:

"But is that enough for the Hashtable to determine they are identical objects? Unfortunately, no. If the Hashtable finds two objects with the same hash, it calls their Equals method to see whether the two objects are in fact equal. Again, the default implementation of Object.Equals will return false if the two objects are two different instances of the same class. So we need to also add an override of the Equals method to our class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!