简洁的方式现场哈希码结合? [英] Concise way to combine field hashcodes?

查看:200
本文介绍了简洁的方式现场哈希码结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个实现GetHashCode的方式 - 在它必须这样做 - 由乔恩飞碟双向的此处。重复他的代码:

One if the ways to implement GetHashCode - where it's required to do so - is outlined by Jon Skeet here. Repeating his code:

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}



滚动这段代码用手可容易出错虫子可能是微妙/很难发现(你交换 + * 误?),也可以是硬要记住不同类型的组合规则,我不喜欢写作花费心力/一遍又一遍地审查同样的事情再次不同领域和类别。它也可以混淆的最重要的一个细节(我清楚地记得,包括所有的字段?),在反复的噪声。

Rolling this code by hand can be error-prone and bugs can be subtle/hard to spot (did you swap + and * by mistake?), it can be hard to remember the combination rules for different types, and I don't like expending mental effort on writing/reviewing the same thing over and over again for different fields and classes. It can also obfuscate one of the most important details (did I remember to include all the fields?) in repetitive noise.

有没有使用.NET库场哈希码结合了简洁的方式?。很显然,我可以写我自己的,但如果有一些惯用/内置我喜欢这一点。

Is there a concise way to combine field hashcodes using the .net library?. Obviously I could write my own, but if there's something idiomatic/built-in I'd prefer that.

作为一个实例,在Java(注册使用JDK7)我能实现上述使用

As an example, in Java (using JDK7) I can achieve the above using:

   @Override
   public int hashCode()  
   {  
      return Objects.hash(field1, field2, field3);  
   }  

这确实有助于消除bug和集中在重要的细节。

This really helps to eliminate bugs and focus in the important details.

动机:我碰到一个C#类,它需要一个覆盖的GetHashCode(),但它的方式结合来其各种成分的哈希码有一些严重的错误。对于合并的哈希码的库函数将是避免这种错误非常有用

Motivation: I came across a C# class which requires an overridden GetHashCode(), but the way it combined the hashcodes of its various constituents had some severe bugs. A library function for combining the hashcodes would be useful for avoiding such bugs.

推荐答案

有些人使用:

Tuple.Create(lastName, firstName, gender).GetHashCode()

它提到 MSDN上在 Object.GetHashCode() ,与警告:

It's mentioned on MSDN at Object.GetHashCode(), with the warning:

但是请注意,该实例化一个元组对象的性能开销可能显著影响存储大量在哈希表的对象的应用程序的整体性能。

Note, though, that the performance overhead of instantiating a Tuple object may significantly impact the overall performance of an application that stores large numbers of objects in hash tables.

聚合组成哈希值是由 System.Tuple ,它希望有过一些想法进入它提供的逻辑...

The logic of aggregating the constituent hashes is provided by System.Tuple, which hopefully has had some thought go into it...

更新:值得注意的是@瑞安在评论中观察,这似乎只用大小的任何元组的最后8元素> 8

Update: it is worth noting @Ryan's observation in the comments that this only appears to use the last 8 elements of any Tuple of Size>8.

这篇关于简洁的方式现场哈希码结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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