C#:重写GetHashCode,这是什么代码呢?

编程入门 行业动态 更新时间:2024-10-27 22:21:22
本文介绍了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,这是什么代码呢?

本文发布于:2023-11-02 08:49:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重写   代码   这是什么   GetHashCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!