【发布时间】:2014-11-27 10:45:30
【问题描述】:
这重现了问题:
program Project1;
{$APPTYPE CONSOLE}
uses
Generics.Collections;
type
TStringRec = record
s1 : string;
s2 : string;
end;
TGetHash<TKey,TValue> = class(TEnumerable<TPair<TKey,TValue>>)
public
type
TItem = record
HashCode: Integer;
Key: TKey;
Value: TValue;
end;
TItemArray = array of TItem;
public
FItems: TItemArray;
end;
var
LCrossRef : TDictionary<TStringRec, integer>;
LRec : TStringRec;
i : integer;
begin
LCrossRef := TDictionary<TStringRec, integer>.Create();
LRec.s1 := 'test1';
LRec.s2 := 'test2';
LCrossRef.Add(LRec, 1);
LRec.s1 := 'test1';
LRec.s2 := 'test2';
if LCrossRef.TryGetValue(LRec, i) then begin
writeln('ok');
end else begin
LCrossRef.Add(LRec, 1);
for i := Low(TGetHash<TStringRec, integer>
(LCrossRef).FItems)
to High(TGetHash<TStringRec, integer>
(LCrossRef).FItems) do
WriteLn(TGetHash<TStringRec, integer>(LCrossRef).FItems[i].HashCode);
WriteLn('not ok');
end;
ReadLn;
end.
字典无法检索项目并为包含相同字符串的记录生成不同的HashCode。
这在QC-#122791 中有部分说明,但使用打包记录的解决方法不适用于字符串记录(至少当TStringRec 声明为packed record 时,上述示例也会失败)。
是否有合理的解决方法?
我目前的策略是将原本会进入记录的字符串连接起来,并改用TDictionary<string, TValue>,但这自然不能令人满意。
【问题讨论】:
-
如何将 TObjectDictionary 与为您的特定类型实现 GetHashCode 的自定义 IEqualityComparer 一起使用?
-
@VilleKrumlinde 你不是说
TObjectDictionary。这里没有对象所有权。 -
实现
IEqualityComparer绝对是一条路。 -
这个答案可能有用并为您节省一些代码:stackoverflow.com/questions/27820171/…
标签: delphi generics dictionary hash delphi-xe2