你如何在对象上实现GetHashCode()? [重复]

时间:2022-09-02 09:31:38

Duplicate: What is the best algorithm for an overridden System.Object.GetHashCode?

重复:重写的System.Object.GetHashCode的最佳算法是什么?


If you've written an object with a variety of data-members, how do you intelligently implement GetHashCode()?

如果您编写了一个包含各种数据成员的对象,那么如何智能地实现GetHashCode()?

One developer told me he just XORs (^ operator) the Hash of relevant data-fields, but I am unconvinced this is a "best-practices" implementation.

一位开发人员告诉我他只是XOR(^运算符)相关数据字段的哈希,但我不相信这是一个“最佳实践”实现。

If I had my way, there would be functions Object.CombineHashes(Object[]), and/or Object.CombineHashes(int[]) to help intelligently build hashes of complex objects.

如果我按照自己的方式,将有函数Object.CombineHashes(Object [])和/或Object.CombineHashes(int [])来帮助智能地构建复杂对象的哈希。

How would you write these functions?

你会怎么写这些功能?

1 个解决方案

#1


I did a quick and dirty implementation of a bunch of members by concatenating them with pipes and then getting the hascode of that:

我通过将它们与管道连接起来,然后获取其中的hascode,对一堆成员进行了快速而又脏的实现:

(Member1.ToString() + "|" + Member2.ToString()).GetHasCode();

In my case, I know that I won't ever have pipes in the members so I knew the results would be pretty good.

在我的情况下,我知道我不会在成员中使用管道,所以我知道结果会很好。

Actually, in my case I implemented ToString for debugging purposes so I just used that:

实际上,在我的情况下,我实现了ToString用于调试目的所以我只是用它:

this.ToString().GetHashCode();

Xors is another approach I've often seen.

Xors是我经常看到的另一种方法。

#1


I did a quick and dirty implementation of a bunch of members by concatenating them with pipes and then getting the hascode of that:

我通过将它们与管道连接起来,然后获取其中的hascode,对一堆成员进行了快速而又脏的实现:

(Member1.ToString() + "|" + Member2.ToString()).GetHasCode();

In my case, I know that I won't ever have pipes in the members so I knew the results would be pretty good.

在我的情况下,我知道我不会在成员中使用管道,所以我知道结果会很好。

Actually, in my case I implemented ToString for debugging purposes so I just used that:

实际上,在我的情况下,我实现了ToString用于调试目的所以我只是用它:

this.ToString().GetHashCode();

Xors is another approach I've often seen.

Xors是我经常看到的另一种方法。