我有一个使用 TDictionary 的情况:
var D: TDictionary<string, integer>;
begin
D := TDictionary<string, integer>.Create(TCustomEqualityComparer.Create());
try
D.Add('One', 1);
D.Add('Two', 2);
D.Add('Three', 3);
showmessage(inttostr(D.Items['One']));
showmessage(inttostr(D.Items['TWO']));
finally
D.Free;
end;
end;
类TCustomEqualityComparer是从Generics Defaults TEqualityComparer(Delphi)复制而来,并对GetHashCode方法进行了微小修改:
TCustomEqualityComparer = class(TEqualityComparer<string>)
public
function Equals(const Left, Right: string): Boolean; override;
function GetHashCode(const Value: string): Integer; override;
end;
function TCustomEqualityComparer.Equals(const Left, Right: string): Boolean;
begin
Result := SameText(Left, Right);
end;
function TCustomEqualityComparer.GetHashCode(const Value: string): Integer;
begin
Result := BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0);
end;
我希望 TCustomEqualityComparer 能够对键值执行不区分大小写的匹配。例如:
D.Items['TWO']
然而,我得到了一个“未找到项目”的异常。我正在使用Delphi 2010版本14.0.3513.24210。
有人知道我的代码哪里出了问题吗?