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

空扰寡人 提交于 2019-12-07 02:40:29

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!