加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – GetHashCode用于多个布尔值

发布时间:2020-12-15 23:38:32 所属栏目:百科 来源:网络整理
导读:在下面的StackOverflow question中,Jon Skeets的答案指定了一个很好的实现是…… // Note: Not quite FNV!public override int GetHashCode(){ unchecked // Overflow is fine,just wrap { int hash = (int) 2166136261; // Suitable nullity checks etc,of
在下面的StackOverflow question中,Jon Skeets的答案指定了一个很好的实现是……

// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine,just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc,of course :)
        hash = (hash * 16777619) ^ bool1.GetHashCode();
        hash = (hash * 16777619) ^ bool2.GetHashCode();
        return hash;
    }
}

如果两个字段都是bool怎么办?这仍然是一个很好的实现还是会有点矫枉过正?如果这有点过分,当所有字段都是bool类型时,推荐的实现GetHashCode的方法是什么?

在我的情况下,我只比较两个布尔.

解决方法

如果少于30个bool字段,则可以通过将每个bool视为哈希码值中的单个位来实现 perfect哈希方案. “完美”我的意思是哈希等式将等同于实际相等(与“普通”哈希方案相对,其中实际相等意味着哈希相等,但反之亦然).

代码如下所示:

public override int GetHashCode() {
    var hash = 0;
    if (field1)
        hash |= 1<<0;
    if (field2)
        hash |= 1<<1;
    if (field3)
        hash |= 1<<2;
    if (field4)
        hash |= 1<<3;
    return hash;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读