【发布时间】:2009-10-23 06:11:09
【问题描述】:
我有一个使用 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。
有人知道我的代码出了什么问题吗?
【问题讨论】:
标签: delphi