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

后端 未结 4 1401
予麋鹿
予麋鹿 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:30

    You can only correctly implement GetHashCode() if the Id property is immutable for the lifetime of an instance (or at least for the time that its hash needs to be used, such as while the object is in a map or other collection requiring the hash).

    Assuming that it is, you can just use the value of Id as the hash for all valid values and then use a fixed hash for null. I can't remember what the most appropriate is for this, but I would assume a randomly selected value for null(randomly selected prior to compilation, not at runtime) or the median value of valid Id values (i.e. halfway between 0 and int.Max).

提交回复
热议问题