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

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

    What about using the type as part of the hash code?
    Would this be a good implementation?

    public class Foo
    {
        public int Id { get; set; }
    
        // other properties here
        // ......
    
        public override int GetHashCode()
        {
            int hash = 37;
            hash = hash * 23 + typeof(Foo).GetHashCode();
            hash = hash * 23 + Id.GetHashCode();
            return hash;
        }
    }
    

提交回复
热议问题