简体   繁体   English

GetHashCode的好习惯?

[英]GetHashCode good practice?

For a Delphi project (built with RAD Studio XE7), I want to create a dictionary of brushes. 对于Delphi项目(使用RAD Studio XE7构建),我想创建一个画笔字典。 Each dictionary item contains a TMyBrush object as key, that describes the brush to retrieve, and a GDI+ brush as value. 每个字典项包含一个TMyBrush对象作为键,描述要检索的画笔,以及GDI +画笔作为值。

The TMyBrush class contains 3 fields TMyBrush类包含3个字段

  • An enumerated type to determine the kind of brush (solid, gradient, ...) 用于确定画笔类型的枚举类型(实体,渐变,......)
  • A TBrushInfo class that describes the brush content (color, wrap mode, ...) 描述画笔内容的TBrushInfo类(颜色,换行模式......)
  • A TRect that represents a clamp field 表示钳位字段的TRect

In my dictionary, I want to retrieve a brush based on his characteristics, and not on his instance. 在我的字典中,我想根据他的特征检索画笔,而不是他的实例。 For example, I want to get a black solid brush from my dictionary by creating a local TMyBrush instance, configuring it to black solid, and getting the matching GDI+ value using the TryGetValue() function. 例如,我希望通过创建本地TMyBrush实例,将其配置为黑色实体,并使用TryGetValue()函数获取匹配的GDI +值,从我的字典中获取黑色实心画笔。 For that, I created a TMyBrushComparer. 为此,我创建了一个TMyBrushComparer。

Writing the Equals() function isn't a problem for me. 编写Equals()函数对我来说不是问题。 However I don't know what is the best practice to write the GetHashCode() function. 但是我不知道编写GetHashCode()函数的最佳做法是什么。 I would tend to write a function like this: 我倾向于写一个这样的函数:

function TMyBrushComparer.GetHashCode(const pValue: TMyBrush): Integer;
begin
    Result := BobJenkinsHash(pValue, SizeOf(TMyBrush), 0);
end;

however I feel that is not a very good practice, it is correct? 但是我觉得这不是一个很好的做法,这是正确的吗? So, what is the best practice to write a good GetHashCode() function for my TMyBrushComparer? 那么,为我的TMyBrushComparer编写一个好的GetHashCode()函数的最佳实践是什么?

Regards 问候

The code in the question hashes the address of the object rather than its value and so is not consistent with your definition of equality. 问题中的代码会散列对象的地址而不是其值,因此与您的相等定义不一致。

Your definition of equality is that three of the fields are equal. 你对平等的定义是三个领域是平等的。 Your hash function should match that definition. 您的哈希函数应该与该定义匹配。 Hash each of the three fields, and combine the values, for instance using the approach outlined here: https://stackoverflow.com/a/263416/505088 散列三个字段中的每一个,并组合这些值,例如使用此处概述的方法: https//stackoverflow.com/a/263416/505088

Two of your fields are value types. 您的两个字段是值类型。 They are easy to hash to match value identity. 它们很容易哈希以匹配值身份。 The brush info field appears to be a reference type. 画笔信息字段似乎是引用类型。 So again you need to decide what form of identity you want (reference identity, value identity, or perhaps something else) and then implement matching equality test and hash. 因此,您需要再次确定您想要的身份形式(引用标识,值标识或其他内容),然后实现匹配的相等性测试和哈希。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM