下面是一個簡單的程序,它顯示了使用記錄和對象與TDictionary
不同的處理。
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Generics.Collections;
type
TMyRecord = record
Field : Integer;
end;
TMyObject = class
Field : Integer;
end;
procedure UseObjectDict;
var
LDict : TDictionary<TGUID, TMyObject>;
LValue : TMyObject;
begin
write('TMyObject: ');
LDict := TObjectDictionary<TGUID, TMyObject>.Create([doOwnsValues]);
try
// populate
while LDict.Count < 10 do
begin
LDict.Add(TGuid.NewGuid, TMyObject.Create);
end;
// update
for LValue in LDict.Values do
begin
LValue.Field := LValue.Field + 1;
end;
// output
for LValue in LDict.Values do
begin
write(LValue.Field, ', ');
end;
Writeln;
finally
LDict.Free;
end;
end;
procedure UseRecordDict;
var
LDict : TDictionary<TGUID, TMyRecord>;
LKey : TGUID;
LValue : TMyRecord;
begin
write('TMyRecord: ');
LDict := TDictionary<TGUID, TMyRecord>.Create;
try
// populate
while LDict.Count < 10 do
begin
LValue.Field := 0;
LDict.Add(TGuid.NewGuid, LValue);
end;
// update
for LKey in LDict.Keys do
begin
LValue.Field := LDict[LKey].Field + 1;
LDict.AddOrSetValue(LKey, LValue);
end;
// output
for LValue in LDict.Values do
begin
write(LValue.Field, ', ');
end;
Writeln;
finally
LDict.Free;
end;
end;
begin
ReportMemoryLeaksOnShutdown := True;
try
UseObjectDict;
UseRecordDict;
except
on E : Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
ReadLn;
end.
您可以使用TDictionary。值 –
2013-03-01 21:59:39
您希望能夠修改for循環中的鍵或值嗎?如果你只是想操作數值 – Petesh 2013-03-01 22:00:24
@SirRufo,Values是隻讀啓動器 – 2013-03-01 22:04:06