什么是推动在平等和GetHash code的最佳策略是什么? [英] What's the best strategy for Equals and GetHashCode?

查看:115
本文介绍了什么是推动在平等和GetHash code的最佳策略是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与一个域模型,并思考我们要实现在.NET这两种方法的不同方式。什么是您的preferred策略?

这是我目前的执行情况:

 公众覆盖布尔等于(obj对象)
    {
        VAR newObj = OBJ为MyClass的;

        如果(NULL!= newObj)
        {
            返回this.GetHash code()== newObj.GetHash code();
        }
        其他
        {
            返回base.Equals(OBJ);
        }
    }

    //由于这是我可以用it's标识的实体
    //当我不有一个ID我通常做的属性的组合键
    公众覆盖INT GetHash code()
    {
        返回的String.Format(MyClass的{0},this.Id.ToString())GetHash code()。
    }
 

解决方案

假设情况下都是平等的,因为散列codeS相等是错误的。

我猜你的实现GetHash code是确定的,但我通常使用的东西,类似于这样:

 公众覆盖INT GetHash code(){
    返回object1.GetHash code ^ intValue1 ^(intValue2<< 16);
}
 

I'm working with a domain model and was thinking about the various ways that we have to implement this two methods in .NET. What is your preferred strategy?

This is my current implementation:

    public override bool Equals(object obj)
    {
        var newObj = obj as MyClass;

        if (null != newObj)
        {
            return this.GetHashCode() == newObj.GetHashCode();
        }
        else
        {
            return base.Equals(obj);
        }
    }

    //Since this is an entity I can use it´s Id
    //When I don´t have an Id I usually make a composite key of the properties
    public override int GetHashCode()
    {
        return String.Format("MyClass{0}", this.Id.ToString()).GetHashCode();
    }

解决方案

Assuming that the instances are equal because the hash codes are equal is wrong.

I guess your implementation of GetHashCode is OK, but I usually use things similar to this:

public override int GetHashCode() {
    return object1.GetHashCode ^ intValue1 ^ (intValue2 << 16);
}

这篇关于什么是推动在平等和GetHash code的最佳策略是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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