且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编译器生成GetHash code()

更新时间:2022-05-01 01:46:45

看一看什么是C#编译器为匿名类型。基本上它是同类型的哈希,因为我会写我自己:

Have a look at what the C# compiler does for anonymous types. Basically it's the same sort of hash as I'd write myself:

public override int GetHashCode()
{
    int hash = 17;
    hash = 31 * hash + field1.GetHashCode();
    hash = 31 * hash + field2.GetHashCode();
    // etc
    return hash;
}

(你需要一些无效检查,当然也。)

(You need some nullity checking as well, of course.)

我认为这是一个好主意,要做到这一点(和平等覆盖)恒定类型,但一般的没有的为可变类型。值类型应该总是是一成不变的呢 - 引用类型可以去任何一种方式。请问您的语言有不可改变的任何内置的概念?当然,这会出问题,如果你的类型是浅不可改变的,但包含可变类型其覆盖 GetHash code 来表示的电流的对象的状态。这种类型一般会是痛苦的反正。

I think it's a good idea to do this (and equality override) for immutable types, but generally not for mutable types. Value types should almost always be immutable anyway - reference types can go either way. Does your language have any built-in notion of immutability? Of course, this will go wrong if your type is "shallow immutable" but contains mutable types which override GetHashCode to indicate the current state of the object. Such types would generally be painful anyway.

在一般虽然,我认为这是在许多情况下,合理的自动生成的平等和哈希codeS - 事实上,我想这是C#5名为类型的一部分​​呢:我想要的命名的,否则具有相同的功能,匿名类型。类型

In general though, I think it's reasonable in many cases to autogenerate equality and hash codes - indeed, I'd like this to be part of C# 5 for named types too: I want an easy way of naming types which otherwise have the same features as anonymous types.