C#:重写GetHashCode,这是什么代码呢? [英] C#: override GetHashCode, what does this code do?

查看:173
本文介绍了C#:重写GetHashCode,这是什么代码呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的 NHibernate的3初学者指南中找到的代码覆盖的GetHashCode 。我不明白为什么它使用结果397 * 397。如果他只是用于生成唯一的结果??一个随机数



我们可不可以 GetHashCode的的名字,中间名和姓氏,然后结合在一起使用^,也应该产生一个唯一的结果。

 公共覆盖INT的GetHashCode()
{
选中
{
VAR的结果= FirstName.GetHashCode();
结果=(结果* 397)^(中间名= NULL MiddleName.GetHashCode():?0);
结果=(结果* 397)^ LastName.GetHashCode();
返回结果;
}
}


解决方案

乘法由给定的数字,因为每个组合的一部分,中间散列码将意味着合并后的排序有代码将不会是无关的。



如果你只是做了一个独家或这三个名称部分,然后在约翰·威廉·詹姆斯将给予相同的散列码为詹姆斯·威廉约翰。



397 被选择,因为它是一个素数足够大足以使散列码溢出,这有助于产生的散列码良好分布



的溢流这是代码有坐一个选中块内部的原因。


Here's the code I found in the Nhibernate 3 Beginners Guide to override GetHashCode. I don't understand why it uses result * 397. If 397 just a random number he use to generate unique result??

Can we just GetHashCode for firstname, middlename and lastname, then combine it together using ^, it should also generate an unique result.

public override int GetHashCode()
{
   unchecked
   {
       var result = FirstName.GetHashCode();
       result = (result*397) ^ (MiddleName != null ? MiddleName.GetHashCode() : 0);
       result = (result*397) ^ LastName.GetHashCode();
       return result;
   }
}

解决方案

Multiplying the intermediate hash code by a given number as part of each combination will mean the ordering of the combined has codes will not be irrelevant.

If you just did an exclusive or on the three name parts, then "John William James" would give the same hash code as "James William John".

397 is chosen because it is a prime number large enough sufficient to cause the hash code to overflow, and this helps generate a good distribution of hash codes.

The overflow is the reason this code has to sit inside an unchecked block.

这篇关于C#:重写GetHashCode,这是什么代码呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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