Search code examples
delphiparameter-passingrecorddelphi-xe7

How to pass any record (any type) into Delphi xe7 function as parameter?


I want to define a function that gets an record (in any type) and give us the fields of that as string. My problem is that how can I pass record to function as parameter? How to declare the parameter?

Function GetRecordFields(MyRecord: any record type): string
var
  ctx   : TRttiContext;
  t     : TRttiType;
  field : TRttiField;
begin
 result := '';
 ctx := TRttiContext.Create;
 for field in ctx.GetType(TypeInfo(MyRecord)).GetFields do
 begin
   t := field.FieldType;
   result := result + ' | ' + Format('Field : %s : Type : %s',[field.Name,field.FieldType.Name]);
 end;
end;

Solution

  • Use Generics, eg:

    type
      TRecordHlpr<T: record> = class
      public
        class function GetFields(const Rec: T): string;
      end;
    
    function TRecordHlpr<T>.GetFields(const Rec: T): string;
    var
      ctx   : TRttiContext;
      t     : TRttiType;
      field : TRttiField;
    begin
     Result := '';
     ctx := TRttiContext.Create;
     for field in ctx.GetType(TypeInfo(T)).GetFields do
     begin
       t := field.FieldType;
       Result := Result + ' | ' + Format('Field : %s : Type : %s : Value : %s', [field.Name, field.FieldType.Name, field.GetValue(@Rec).AsString]);
     end;
    end;
    

    type
      TMyRecord = record
        // fields here...
      end;
    
    var
      rec: TMyRecord;
      S: String;
    begin
      // fill rec as needed...
      S := TRecordHlpr<TMyRecord>.GetFields(rec);
    end;