What is the correct implementation for GetHashCode() for entity classes?

后端 未结 4 1350
予麋鹿
予麋鹿 2021-02-01 07:45

Below is a sample implementation of overriding Object.Equals() for an entity base class from which all other entities in an application derive.

All entity classes have t

4条回答
  •  旧巷少年郎
    2021-02-01 08:38

    What Jon Skeet answered is a good solution, however, you might want to add an unchecked code block to allow integer overflowing

    unchecked
    {
      int hash = ...;
      return hash
    }
    

    https://msdn.microsoft.com/en-us/library/khy08726(v=vs.140).aspx

    If neither checked nor unchecked is specified, the default context depends on external factors such as compiler options.

    I'd also like to add, again, that using base.GetHashCode() on POCO's will call the default object.GetHashCode. That's definitely not what you want...

提交回复
热议问题