结合字段哈希码的简洁方法? [英] Concise way to combine field hashcodes?

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

问题描述

Jon Skeet 概述了实现 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);  
   }  

这确实有助于消除错误并专注于重要的细节.

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()

Object.GetHashCode(),带有警告:

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

但请注意,实例化 Tuple 对象的性能开销可能会显着影响在哈希表中存储大量对象的应用程序的整体性能.

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...

更新:值得注意的是@Ryan 在评论中的观察,这似乎只使用任何大小>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天全站免登陆