General advice and guidelines on how to properly override object.GetHashCode()

前端 未结 11 1674
终归单人心
终归单人心 2020-12-01 00:09

According to MSDN, a hash function must have the following properties:

  1. If two objects compare as equal, the GetHashCode method for each object m

11条回答
  •  再見小時候
    2020-12-01 00:41

    How to make sure the hash code stays the same all through the object lifetime. (MSDN Property #2) Especially when the equality is based upon mutable fields. (MSDN Property #1)

    You seem to misunderstand Property #2. The hashcode doesn't need to stay the same thoughout the objects lifetime. It just needs to stay the same as long as the values that determine the outcome of the equals method are not changed. So logically, you base the hashcode on those values only. Then there shouldn't be a problem.

提交回复
热议问题