Why GetHashCode is in Object class?

前端 未结 7 1589
故里飘歌
故里飘歌 2021-01-04 20:57

Why GetHashCode is part of the Object class? Only small part of the objects of the classes are used as keys in hash tables. Wouldn\'t it be better to have a separate interfa

相关标签:
7条回答
  • 2021-01-04 21:28

    Only small part of the objects of the classes are used as keys in hash tables

    I would argue that this is not a true statement. Many classes are often used as keys in hash tables - and object references themselves are very often used. Having the default implementation of GetHashCode exist in System.Object means that ANY object can be used as a key, without restrictions.

    This seems much nicer than forcing a custom interface on objects, just to be able to hash them. You never know when you may need to use an object as the key in a hashed collection.

    This is especially true when using things like HashSet<T> - In this case, often, an object reference is used for tracking and uniqueness, not necessarily as a "key". Had hashing required a custom interface, many classes would become much less useful.

    0 讨论(0)
提交回复
热议问题