您显示的代码正在尝试使用泛型类,但不包括类型。
我不确定在以前的 Delphi 版本中编译器是否从声明中推断出类型,但通常你必须声明类型,如下所示:
uses Generics.Defaults, Generics.Collections;
...
sortedDictKeys := TList<Integer>.Create(dict.Keys);
try
sortedDictKeys.Sort(TComparer<Integer>.Construct(
function (const L, R: integer): integer
begin
result := R - L;
end
)) ;
for i in sortedDictKeys do
log.Lines.Add(Format('%d, %s', [i, dict.Items[i]]));
finally
sortedDictKeys.Free;
end;
我从您链接的 about.com 文章中获得了代码,并对其进行了编译,但我没有对其进行测试。
根据评论中的要求,完整的功能如下所示:
var
dict : TDictionary<integer, char>;
sortedDictKeys : TList<integer>;
i, rnd : integer;
c : char;
begin
log.Clear;
log.Text := 'TDictionary usage samples';
Randomize;
dict := TDictionary<integer, char>.Create;
try
//add some key/value pairs (random integers, random characters from A in ASCII)
for i := 1 to 20 do
begin
rnd := Random(30);
if NOT dict.ContainsKey(rnd) then dict.Add(rnd, Char(65 + rnd));
end;
//remove some key/value pairs (random integers, random characters from A in ASCII)
for i := 1 to 20 do
begin
rnd := Random(30);
dict.Remove(rnd);
end;
//loop elements - go through keys
log.Lines.Add('ELEMENTS:');
for i in dict.Keys do
log.Lines.Add(Format('%d, %s', [i, dict.Items[i]]));
//do we have a "special" key value
if dict.TryGetValue(80, c) then
log.Lines.Add(Format('Found "special", value: %s', [c]))
else
log.Lines.Add(Format('"Special" key not found', []));
//sort by keys ascending
log.Lines.Add('KEYS SORTED ASCENDING:');
sortedDictKeys := TList<integer>.Create(dict.Keys);
try
sortedDictKeys.Sort; //default ascending
for i in sortedDictKeys do
log.Lines.Add(Format('%d, %s', [i, dict.Items[i]]));
finally
sortedDictKeys.Free;
end;
//sort by keys descending
log.Lines.Add('KEYS SORTED DESCENDING:');
sortedDictKeys := TList<Integer>.Create(dict.Keys);
try
sortedDictKeys.Sort(TComparer<Integer>.Construct(
function (const L, R: integer): integer
begin
result := R - L;
end
)) ;
for i in sortedDictKeys do
log.Lines.Add(Format('%d, %s', [i, dict.Items[i]]));
finally
sortedDictKeys.Free;
end;
finally
dict.Free;
end;
end;