加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi TObjectDictionary有一个类实例键

发布时间:2020-12-15 09:15:40 所属栏目:大数据 来源:网络整理
导读:参见英文答案 Use objects as keys in TObjectDictionary????????????????????????????????????2个 我有以下课程: TTest = classprivate FId: Integer; FSecField: Integer; FThirdField: Integer;public constructor Create(AId,ASecField,AThirdField: In
参见英文答案 > Use objects as keys in TObjectDictionary????????????????????????????????????2个
我有以下课程:

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)) then
      ShowMessage('Match found')
    else
      ShowMessage('Match not found');

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

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

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

解决方法

实例引用变量的默认相等比较器比较引用而不是对象.因此,您获得对象身份而不是价值身份.

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

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

其中EqualityComparison,Hasher是比较和散列函数.它们可以像这样实现:

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读