记录此再现的问题:TDictionary散列被分解为字符串
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和自定义的IEqualityComparer来为您的特定类型实现GetHashCode? – 2014-10-02 12:44:47
@VilleKrumlinde你不是指'TObjectDictionary'。这里没有对象所有权。 – 2014-10-02 12:57:17
实现'IEqualityComparer'绝对是一种方法。 – 2014-10-02 18:52:39