Why GetHashCode is in Object class?

前端 未结 7 1631
故里飘歌
故里飘歌 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:05

    It was a design mistake copied from Java, IMO.

    In my perfect world:

    • ToString would be renamed ToDebugString to set expectations appropriately
    • Equals and GetHashCode would be gone
    • There would be a ReferenceEqualityComparer implementation of IEqualityComparer: the equals part of this is easy at the moment, but there's no way of getting an "original" hash code if it's overridden
    • Objects wouldn't have monitors associated with them: Monitor would have a constructor, and Enter/Exit etc would be instance methods.

    Equality (and thus hashing) cause problems in inheritance hierarchies in general - so long as you can always specify the kind of comparison you want to use (via IEqualityComparer) and objects can implement IEquatable themselves if they want to, I don't see why it should be on Object. EqualityComparer.Default could use the reference implementation if T didn't implement IEquatable and defer to the objects otherwise. Life would be pleasant.

    Ah well. While I'm at it, array covariance was another platform mistake. If you want language mistakes in C#, I can start another minor rant if you like ;) (It's still by far my favourite language, but there are things I wish had been done differently.)

    I've blogged about this elsewhere, btw.

提交回复
热议问题