我想做这样的事情,但它不会编译因为无法分配对.
var
MyDictionary: TDictionary<TGuid, TCustomRecord>;
Pair: TPair<TGuid, TCustomRecord>;
begin
// ... create and populate my dictionary ...
foreach Pair in MyDictionary do
begin
PairRef.Value.MyField := PairRef.Value.MyField + 1;
end;
end
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我知道如何通过更多代码实现这一目标,我正在寻找简洁易读的东西.
这是一个简单的程序,它显示了使用记录和对象的不同处理方式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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1165 次 |
| 最近记录: |