delphi遍历record
通过rtti遍历record,支持delphi2010以上版本,更低版本不支持。
可以遍历record的field的名称、类型和长度。
uses system.rtti
type
Ttest = record
str: string;
i32: Integer;
i64: Int64;
sgl: Single;
dbl: Double;
ext: Extended;
dt: TDateTime;
bt: Byte;
end;
//遍历record
procedure loopRecord(aTypeInfo, instance: Pointer);
begin
var RTX: TRttiContext;
var RT: TRttiType;
var RF: TRttiField;
RT := RTX.GetType(aTypeInfo);
for RF in RT.AsRecord.GetFields do
Memo1.Lines.Add(RF.Name + ' ' + RF.GetValue(instance).ToString + ' ' + RF.FieldType.ToString + ' ' + RF.RttiDataSize.ToString);
RTX.Free;
RF.Free;
RT.Free;
end;
procedure TForm1.button6Click(Sender: TObject);
begin
var t: Ttest;
t.str := 'str';
t.i32 := 32;
t.i64 := 64;
t.sgl := 1.1;
t.dbl := 2.2;
t.ext := 3.3;
t.dt := Now;
t.bt := 1;
loopRecord(TypeInfo(Ttest), @t);
end;
执行结果
str str string 15
i32 32 Integer 15
i64 64 Int64 15
sgl 1.10000002384186 Single 15
dbl 2.2 Double 15
ext 3.3 Extended 15
dt 2022-05-13 20:01:47 TDateTime 14
bt 1 Byte 14