我想定义一个获取记录(任何类型)并将其字段作为字符串的函数。我的问题是如何传递记录以用作参数?如何声明参数?
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句