Compiler Generated GetHashCode()

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 10:55:13

问题


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:

  • Is this possible, does the compiler know enough about the type(s) involved to do a reasonable job implementing the method?
  • Should I do this for value types, reference types, or both?
  • What is a reasonable GetHashCode algorithm for the compiler to generate which includes support for null properties and so forth?
  • Has this been done in another language/compiler that I can look at?
  • If this isn't possible or is a really bad idea, why?

Thanks


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/3160571/compiler-generated-gethashcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!