base.GetHashCode()如何为结构体实现? [英] How is base.GetHashCode() implemented for a struct?

查看:113
本文介绍了base.GetHashCode()如何为结构体实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在struct中看到了这段代码,我想知道base.GetHashCode的实际作用.

I saw this code recently in a struct and I was wondering what base.GetHashCode actually does.

    public override int GetHashCode()
    {
        var hashCode = -592410294;
        hashCode = hashCode * -1521134295 + base.GetHashCode();
        hashCode = hashCode * -1521134295 + m_Value.GetHashCode();
        return hashCode;
    }

推荐答案

coreclr存储库具有

The coreclr repo has this comment:

操作:我们返回哈希码的算法有点复杂.我们看 对于第一个非静态字段,并获取它的哈希码.如果类型没有 非静态字段,我们返回该类型的哈希码.我们不能接受 静态成员的哈希码,因为该成员的类型与 原始类型,我们将陷入无限循环.

Action: Our algorithm for returning the hashcode is a little bit complex. We look for the first non-static field and get it's hashcode. If the type has no non-static fields, we return the hashcode of the type. We can't take the hashcode of a static member because if that member is of the same type as the original type, we'll end up in an infinite loop.

但是,代码不存在,看来还不算是什么.样本:

However, the code isn't there, and it looks like that's not quite what happens. Sample:

using System;

struct Foo
{
    public string x;
    public string y;
}

class Test
{
    static void Main()
    {
        Foo foo = new Foo();
        foo.x = "x";
        foo.y = "y";
        Console.WriteLine(foo.GetHashCode());
        Console.WriteLine("x".GetHashCode());
        Console.WriteLine("y".GetHashCode());
    }
}

我的盒子上的输出:

42119818
372029398
372029397

更改y的值似乎不会更改foo的哈希码.

Changing the value of y doesn't appear to change the hash code of foo.

但是,如果我们改为将字段设置为int值,则比第一个字段影响更多的输出.

However, if we make the fields int values instead, then more than the first field affects the output.

简而言之:这很复杂,您可能不应该依赖它在运行时的多个版本中保持相同.除非您真的非常有信心,无需在基于哈希的字典/集中将自定义结构用作键,否则我强烈建议覆盖GetHashCodeEquals(并实现IEquatable<T>避免拳击).

In short: this is complex, and you probably shouldn't depend on it remaining the same across multiple versions of the runtime. Unless you're really, really confident that you don't need to use your custom struct as a key in a hash-based dictionary/set, I'd strongly recommend overriding GetHashCode and Equals (and implementing IEquatable<T> to avoid boxing).

这篇关于base.GetHashCode()如何为结构体实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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