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

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

    If you're deriving from something that already overrides GetHashCode I'd implement it as:

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 37;
            hash = hash * 23 + base.GetHashCode();
            hash = hash * 23 + Id.GetHashCode();
            return hash;
        }
    }
    

    A null value of Id will return 0 for Id.GetHashCode().

    If your class just derives from Object, I'd just return Id.GetHashCode() - you do not want to include the object.GetHashCode implementation in your hash code, as that basically ends up being object identity.

    Note that your equality definition won't return true if neither entity has an Id, but the same hashcode will be returned from both objects. You may wish to consider changing your Equals implementation.

提交回复
热议问题