您显示的代码试图使用泛型类,但不包括该类型。
我不知道,如果在以前版本的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;
我仍然得到像8个错误,并在我结束不能编译。我不明白 – user1817376
@user你是否更新了需要的所有地方?你正在使用哪个版本的Delphi?你看到什么错误? –
jachguate
我正在使用Delphi XE3,并且正在关注链接中的示例。它试图更新所有需要的地方。你能告诉我为你编译的代码吗? –
user1817376