警告:" ...重写Object.Equals(对象o),但不重写Object.GetHashCode()" [英] Warning: "... overrides Object.Equals(object o) but does not override Object.GetHashCode()"

查看:1013
本文介绍了警告:" ...重写Object.Equals(对象o),但不重写Object.GetHashCode()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我覆盖了equals()是我的同班同学比较类型GUID的ID值

I overrode the Equals() of my class to compare ID values of type Guid.

然后Visual Studio的警告:

Then Visual Studio warned:

...重写Object.Equals(对象o),但
不重写Object.GetHashCode()

... overrides Object.Equals(object o) but does not override Object.GetHashCode()

所以我当时也推翻了GetHashCode()方法是这样的:

So I then also overrode its GetHashCode() like this:

public partial class SomeClass
{
    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if (obj == null || this.GetType() != obj.GetType()) return false;

        return this.Id == ((SomeClass)obj).Id;
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }
}



这似乎工作。 让我这样做是否正确?记住编号为类型GUID的。 不要紧,我的班是一个实体框架的对象?

It seems to work. Have I done this correctly? Remember Id is of type Guid. Does it matter that my class is an Entity Framework object?

推荐答案

正如其他人所说,在使用的Equals的反思似乎躲躲闪闪。离开那个放在一边,让我们集中精力的GetHashCode。

As others have said, the use of Reflection in Equals seems dodgy. Leaving that aside, let's concentrate on GetHashCode.

有关GetHashCode的,你不能违反的主要规则是如果两个对象相等那么他们必须都具有相同的哈希码。或者,说的等效方法是如果两个对象具有不同的散列码则它们必须相等。您的实现看起来不错那里。

The primary rule for GetHashCode that you must not violate is if two objects are equal then they must both have the same hash code. Or, an equivalent way of saying that is if two objects have different hash codes then they must be unequal. Your implementation looks good there.

你可以自由地违反相反。也就是说,如果两个对象具有相同的哈希代码,然后允许它们相等或不等,您认为合适的。

You are free to violate the converse. That is, if two objects have the same hash code then they are permitted to be equal or unequal, as you see fit.

我假设ID是一个不可改变的属性。如果ID可以通过对象的生命周期变化,那么你可以把一个哈希表对象时出现问题。考虑确保只有永恒不变的属性在计算平等和哈希码使用。

I am assuming that "Id" is an immutable property. If "Id" can change over the lifetime of the object then you can have problems when putting the object in a hash table. Consider ensuring that only immutable properties are used in computing equality and hash code.

您的实现看起来不错,但事实上,你问的问题表明您可能没有一个所有进入建筑物的GetHashCode的实现微妙的因素,扎实抓好。一个良好的开始是我关于这个问题的文章:

Your implementation looks good but the fact that you are asking the question indicates that you might not have a solid grasp of all the subtle factors that go into building an implementation of GetHashCode. A good place to start is my article on the subject:

http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

这篇关于警告:" ...重写Object.Equals(对象o),但不重写Object.GetHashCode()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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