什么是正确的实现GetHash code()为实体类? [英] What is the correct implementation for GetHashCode() for entity classes?

查看:139
本文介绍了什么是正确的实现GetHash code()为实体类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是压倒一切的Object.Equals()一个实体基类,应用程序中的所有其他实体获得的样本实现。

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

所有的实体类都有属性ID,这是一个可为空的int。 (它是什么表的实体类对应的主键。)

All entity classes have the property Id, which is a nullable int. (It's the primary key of whatever table the entity class corresponds to.)

public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;

            if (base.Equals(obj))
                return true;

            return Id.HasValue && ((EntityBase) obj).Id.HasValue &&
                   Id.Value == ((EntityBase) obj).Id.Value;
        }

鉴于这种实现的equals(),你如何正确地实现GetHash code的()?

Given this implementation of Equals(), how do you correctly implement GetHashCode()?

推荐答案

我要实现它的:

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

ID的空值将返回0 Id.GetHash code()。

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

如果你的类只是从Object派生,我只是返回 Id.GetHash code()

If your class just derives from Object, I'd just return Id.GetHashCode()

请注意,您的平等定义的不会的回报如果没有实体有一个ID,但相同的哈希code会从两个对象返回。你不妨考虑改变你的Equals实现。

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.

这篇关于什么是正确的实现GetHash code()为实体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆