Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access all elements of a record using RTTI

Tags:

delphi

rtti

I want to dump a complex / long record into a memo for debugging purpose

 TmyRecord =
     aValue : String 
     aNumber : Real;
     Morenumbers   :  Integer ;
     ....
     ....
  end;

I think Delphi XE 2 RTTI should give me the chance to get the Fieldname , Fieldtype and value within a loop, to write this record to a memo or .....

like image 648
user1769184 Avatar asked May 23 '14 07:05

user1769184


1 Answers

As starting point - record with simple types. For complex fields (array, class etc) explore RTTI unit

type
  TmyRecord = record
    aValue: String;
    aNumber: Real;
    Morenumbers: Integer;
  end;
var
  m: TMyRecord;
  rtype: TRTTIType;
  fields: TArray<TRttiField>;
  i: Integer;
begin
  m.aValue := 'OK';
  m.aNumber := Pi;
  m.Morenumbers := 666;
  rtype := TRTTIContext.Create.GetType(TypeInfo(TMyrecord));
  Memo1.Lines.Add(rtype.ToString);
  fields := rtype.GetFields;
  for i := 0 to High(fields) do
    Memo1.Lines.Add(Format('%s: %s :: %s', [
      fields[i].Name,
      fields[i].FieldType.ToString,
      fields[i].GetValue(@m).ToString]));

output:

TmyRecord
aValue: string :: OK
aNumber: Real :: 3.14159265358979
Morenumbers: Integer :: 666
like image 131
MBo Avatar answered Sep 21 '22 23:09

MBo