如何将任何记录(任何类型)传递给Delphi xe7函数作为参数? [英] How to pass any record (any type) into Delphi xe7 function as parameter?

查看:144
本文介绍了如何将任何记录(任何类型)传递给Delphi xe7函数作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个获取记录(任何类型)并将其字段作为字符串的函数。我的问题是如何传递记录作为参数?如何声明参数?

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;


推荐答案

使用泛型,例如:

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;

这篇关于如何将任何记录(任何类型)传递给Delphi xe7函数作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆