我有一个使用TDictionary的案例:
var D: TDictionary; begin D := TDictionary .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;
从Generics Defaults TEqualityComparer(Delphi)复制类TCustomEqualityComparer,对GetHashCode方法进行微小修改:
TCustomEqualityComparer = class(TEqualityComparer) 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.
有谁知道我的代码有什么问题?
uses System.Generics.Collections, System.Generics.Defaults; var D: TDictionary; begin D := TDictionary .Create(TIStringComparer.Ordinal); // ‹- this is the trick try D.Add('One', 1); . . finally D.Free; end; end;