Delphi TObjectDictionary有一个类实例键

时间:2016-01-13 09:42:18

标签: delphi generics dictionary memory-address

我有以下class

TTest = class
private
  FId: Integer;
  FSecField: Integer;
  FThirdField: Integer;
public
  constructor Create(AId, ASecField, AThirdField: Integer);
  // ..... 
end;

然后我像这样创建一个TObjectDictionary

procedure TMainForm.btnTestClick(Sender: TObject);
var
  TestDict: TObjectDictionary<TTest, string>;
  Instance: TTest;
begin
  TestDict := TObjectDictionary<TTest, string>.Create([doOwnsKeys]);

  try
    TestDict.Add(TTest.Create(1, 1, 1), '');

    if TestDict.ContainsKey(TTest.Create(1, 1, 1)) then
      ShowMessage('Match found')
    else
      ShowMessage('Match not found');

    Instance := TTest.Create(1, 1, 1);
    TestDict.Add(Instance, 'str');

    if TestDict.ContainsKey(Instance) then
      ShowMessage('Match found')
    else
      ShowMessage('Match not found');
  finally
    TestDict.Free;
  end;
end;

结果是:&#34;未找到匹配&#34;,&#34;匹配找到&#34;。我应该怎么做才能比较每个键的字段值而不是它们的地址?

1 个答案:

答案 0 :(得分:3)

实例引用变量的默认相等比较器比较引用而不是对象。所以你得到了对象的身份而不是价值认同。

因此,如果您希望强加价值身份,则需要提供自定义相等比较器。

TestDict := TObjectDictionary<TTest, string>.Create(
  [doOwnsKeys], 
  TEqualityComparer<TTest>.Construct(EqualityComparison, Hasher)
);

其中EqualityComparisonHasher是比较和散列函数。它们可以像这样实现:

EqualityComparison := 
  function(const Left, Right: TTest): Boolean
  begin
    Result := (Left.FId = Right.FId)
      and (Left.FSecField = Right.FSecField)
      and (Left.FThirdField = Right.FThirdField);
  end;

Hasher := 
  function(const Value: TTest): Integer
  begin
    Result := BobJenkinsHash(Value.FId, SizeOf(Value.FId), 0);
    Result := BobJenkinsHash(Value.FSecField, SizeOf(Value.FSecField), Result);
    Result := BobJenkinsHash(Value.FThirdField, SizeOf(Value.FThirdField), Result);
  end;