实施的GetHashCode [英] Implementing GetHashCode

查看:134
本文介绍了实施的GetHashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
什么是一个重写System.Object.GetHashCode最好的算法?

什么构成一个良好的执行GetHashCode方法呢?我做了一些google搜索,并发现了一些goodlines(MSDN),但它似乎是一个逻辑只是操纵存储在类领域的两个数字。是实际的逻辑,这个简单的实现此方法?

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.

这会考虑所有成员,但没有给出很好分布的实现可以在System.Drawing中找到.Point结构。它使用异或的比特在成员结合,这意味着,其中X和Y是相等的所有点得到的哈希码零:

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.

这篇关于实施的GetHashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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