编译器生成GetHash code() [英] Compiler Generated GetHashCode()

查看:133
本文介绍了编译器生成GetHash code()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个编译器的.NET语言运行和的事情之一,我想它做的是自动生成GetHash code的方法,但我有几个问题:

I'm working on writing a compiler for a language running on .net and one of the things I would like it to do is to automatically generate the GetHashCode method, but I have several questions:

  • 这是可能的,该编译器有足够的了解参与做一个合理的工作实施方法的类型(S)?
  • 我应该这样做,值类型,引用类型,或两者兼而有之?
  • 什么是合理的GetHash code算法编译器生成,其中包括对空属性的支持等等?
  • 在这种情形已经在另一种语言/编译器,我可以看看?
  • 完成
  • 如果这是不可能的,或者是非常糟糕的主意,为什么

感谢

推荐答案

看一看什么是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.

这篇关于编译器生成GetHash code()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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