IComparable and Equals()

后端 未结 3 1828
攒了一身酷
攒了一身酷 2020-12-10 15:57

From MSDN

Types that implement IComparable must override Equals.Types that override Equals must also override GetHashCode; otherwise, Hashtable migh

3条回答
  •  盖世英雄少女心
    2020-12-10 16:38

    IComparable is used for comparing two objects - if these are considered equal then Compare will return 0. It would be very unexpected if IComparable.Compare returned zero for two objects, yet obj1.Equals(obj2) returned false since this would imply two different meanings of equality for the objects.

    When a class overrides Equals, it should also override GetHashCode since two equal objects should hash to the same value, and this hash should be based on the fields/properties used in the implementation of equality.

提交回复
热议问题