What's the role of GetHashCode in the IEqualityComparer in .NET?

前端 未结 3 2082
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 21:14

I\'m trying to understand the role of the GetHashCode method of the interface IEqualityComparer.

The following example is taken from MSDN:

using Syst         


        
3条回答
  •  执念已碎
    2020-11-28 21:28

    While it would be possible for a Dictionary to have its GetValue and similar methods call Equals on every single stored key to see whether it matches the one being sought, that would be very slow. Instead, like many hash-based collections, it relies upon GetHashCode to quickly exclude most non-matching values from consideration. If calling GetHashCode on an item being sought yields 42, and a collection has 53,917 items, but calling GetHashCode on 53,914 of the items yielded a value other than 42, then only 3 items will have to be compared to the ones being sought. The other 53,914 may safely be ignored.

    The reason a GetHashCode is included in an IEqualityComparer is to allow for the possibility that a dictionary's consumer might want to regard as equal objects that would normally not regard each other as equal. The most common example would be a caller that wants to use strings as keys but use case-insensitive comparisons. In order to make that work efficiently, the dictionary will need to have some form of hash function that will yield the same value for "Fox" and "FOX", but hopefully yield something else for "box" or "zebra". Since the GetHashCode method built into String doesn't work that way, the dictionary will need to get such a method from somewhere else, and IEqualityComparer is the most logical place since the need for such a hash code would be very strongly associated with an Equals method that considers "Fox" and "FOX" identical to each other, but not to "box" or "zebra".

提交回复
热议问题