简体   繁体   English

GetHashCode返回不同​​的值

[英]GetHashCode returns different Values

I'm using Linq-to-Sql to query a SQL Server database. 我正在使用Linq-to-Sql来查询SQL Server数据库。 This query returns a List of an entity in my database. 此查询返回数据库中实体的List。 My underlying data is NOT changing. 我的基础数据没有变化。

Once I have received the List, I call GetHashCode on it in order to test for equality. 收到列表后,我将在其上调用GetHashCode以测试是否相等。 Oddly, the hash value is always different. 奇怪的是,哈希值总是不同的。 Why would it always be different? 为什么总会有所不同?

Thank you, 谢谢,

Are different beacuse they are different object references. 是不同的,因为它们是不同的对象引用。

You need to override Equals() and GetHashCode() for your object, based on the object data, if you want to behave in that way. 如果要以这种方式运行,则需要根据对象数据为对象覆盖Equals()GetHashCode()

Here you have an example about how to do it, and here a blog post about the guidelines overriding the GetHashCode() method. 这里有一个关于如何操作的示例, 这里有一篇关于覆盖GetHashCode()方法的指南的博客文章。 Hope it helps. 希望能帮助到你。

class TwoDPoint : System.Object
{
    public readonly int x, y;

    public TwoDPoint(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(System.Object obj)
    {
        if (obj == null) return false;

        TwoDPoint p = obj as TwoDPoint;
        if (p == null) return false;

        // Return true if the fields match
        return (x == p.x) && (y == p.y);
    }

    public override int GetHashCode()
    {
        return x ^ y;
    }
}

As Servy said in his comment, keep in mind that even overriding GetHashCode() method, you won't be able to have a collision-free hash with that type of data (ever), you can only reduce the collision rate. 正如Servy在他的评论中所说的那样,请记住,即使重写GetHashCode()方法,您也无法使用该类型的数据进行无冲突哈希(只有),您只能降低冲突率。 You need to use Equals() to ensure objects with the same hash are really the same 您需要使用Equals()来确保具有相同散列的对象真的相同

Did you override GetHashCode() ? 你重写了GetHashCode()吗? If not the default implementation is to give you a hash code based on the reference of the list. 如果不是,则默认实现是根据列表的引用为您提供哈希码。 It will not have anything to do with the contents of the list. 它与列表的内容无关。

So two different instances means two different hash codes. 所以两个不同的实例意味着两个不同的哈希码

To check for list equality override Equals (and GetHashCode() ) on your entity class and use SequenceEqual on the list. 要检查列表相等性,请在实体类上重写Equals (和GetHashCode() ),并在列表中使用SequenceEqual

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM