Is Object.GetHashCode() unique to a reference or a value?

后端 未结 6 1004
南方客
南方客 2020-12-24 12:58

The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work.

  1. If two objects of the same type represent the
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 13:42

    Rules 1 & 3 are contradictory to me.

    To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.

    To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.

    Consider the following example:

    struct Person {
        public readonly string FirstName;
        public readonly string Name;
        public readonly DateTime Birthday;
    
        public int ShoeSize;
    }
    

    People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:

    public int GetHashCode() {
        return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();
    }
    

提交回复
热议问题