Non-readonly fields referenced in GetHashCode()

前端 未结 2 539
深忆病人
深忆病人 2021-01-17 07:26

Started with overriding concepts and I override the methods Equals and GetHashCode.

Primarily I came up with this \"very simple code\":

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 08:08

    If you change the value of a field, used in the hash calculation, after the object had been added to a hash based container like Dictionary or HashSet, you are essentially breaking the inner state of the container. Why is that? Because the object had been stored in a bucket corresponding to a hash value based on its initial state. When the state is changed, e.g. 'age' is modified, the object will continue to live in its old bucket in the hash container although this is not the correct bucket based on its current hash code. This can lead to pretty messy behaviour and a lot of headaches. I've written an article on this topic with some very specific examples, so you may want to check it out.

提交回复
热议问题