How do you implement GetHashCode() on objects?

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


If you've written an object with a variety of data-members, how do you intelligently implement 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.

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.

How would you write these functions?


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

(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:

this.ToString().GetHashCode();

Xors is another approach I've often seen.

链接地址: http://www.djcxy.com/p/39760.html

上一篇: C#GetHashCode()高性能散列算法

下一篇: 你如何在对象上实现GetHashCode()?