When Should a .NET Class Override Equals()? When Should it Not?

后端 未结 4 1100
小鲜肉
小鲜肉 2020-11-30 10:20

The VS2005 documentation Guidelines for Overloading Equals() and Operator == (C# Programming Guide) states in part

Overriding operator == in non-immut

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 10:41

    I don't understand your concerns about GetHashCode in regards to HashSet. GetHashCode just returns a number that helps HashSet internally store and lookup values. If the hash code for an object changes the object doesn't get removed from HashSet, it just won't be stored in the most optimal position.

    EDIT

    Thanks to @Erik J I see the point.

    The HashSet is a performance collection and to achieve that performance it relies completely on GetHashCode being constant for the life of the collection. If you want this performance then you need to follow these rules. If you can't then you'll have to switch to something else like List

提交回复
热议问题