开发者

Implementing GetHashCode [duplicate]

This question already has answers here: Closed 10 years ago开发者_Go百科.

Possible Duplicate:

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

What constitutes a good implementation of the GetHashCode method? I did some googling, and found some goodlines (MSDN) but it seems like the logic just manipulates two numbers stored as fields in the class. Is the actual logic this simple to implement this method?


The minimum requirement is that the hash code should be the same for any given value. So, this implementation works, but the distribution is horrible:

public override int GetHashCode() {
  return 1;
}

To work best, the hash codes should consider all relevant data in the object and be as evenly distributed as possible within the integer range.

An implementation that does consider all members, but doesn't give very good distribution can be found in the System.Drawing.Point structure. It uses XOR to combine the bits in the members, which means that all points where X and Y are equal get the hash code zero:

public override int GetHashCode() {
  return this.X ^ this.Y;
}

One way to get a better distribution is to multiply a member by a prime number and add the next member, repeating as needed:

public override int GetHashCode() {
  return ((this.Value1 * 251) + this.Value2) * 251 + this.Value3;
}

The same method has been used in simple random generators, as it scatters the values pretty well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜