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

前端 未结 11 1693
终归单人心
终归单人心 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:40

    Why do I have to override object.GetHashCode()?

    Overriding this method is important because the following property must always remain true:

    If two objects compare as equal, the GetHashCode method for each object must return the same value.

    The reason, as stated by JaredPar in a blog post on implementing equality, is that

    Many classes use the hash code to classify an object. In particular hash tables and dictionaries tend to place objects in buckets based on their hash code. When checking if an object is already in the hash table it will first look for it in a bucket. If two objects are equal but have different hash codes they may be put into different buckets and the dictionary would fail to lookup the object.

    Related links:

    • Do I HAVE to override GetHashCode and Equals in new Classes?
    • Do I need to override GetHashCode() on reference types?
    • Override Equals and GetHashCode Question
    • Why is it important to override GetHashCode when Equals method is overriden in C#?
    • Properly Implementing Equality in VB

提交回复
热议问题