IEqualityComparer GetHashCode being called but Equals not

前端 未结 4 877
暖寄归人
暖寄归人 2020-12-10 03:47

I have two lists that I am trying to compare. So I have created a class that implements the IEqualityComparer interface, please see below in the bottom section

4条回答
  •  死守一世寂寞
    2020-12-10 04:08

    GetHashCode is intended as a fast but rough estimate of equality, so many operations potentially involving large numbers of comparisons start by checking this result instead of Equals, and only use Equals when necessary. In particular, if x.GetHashCode()!=y.GetHashCode(), then we already know x.Equals(y) is false, so there is no reason to call Equals. Had x.GetHashCode()==y.GetHashCode(), then x might equal y, but only a call to Equals will give a definite answer.

    If you implement GetHashCode in a way that causes GetHashCode to be different for two objects where Equals returns true, then you have a bug in your code and many collection classes and algorithms relying on these methods will silently fail.

提交回复
热议问题