我编写了一个RttiHelper类,除其他外,它可以检索一个类的所有字段名称。该过程成功确定字段是对象还是数组,但无法确定字段是否为记录。遵循代码:
unit Form1
interface
uses RttiHelper;
type
tMyRec = Record
...
end;
...
implementation
var MyRec : tMyRec;
procedure FormCreate (Sender: tObject);
begin
SetRec (@MyRec);
end;
unit RttiHelper
interface
type
tObjRec = class
Rec : Pointer;
end;
...
tRttiHelperClass = class (tObject)
private
fObjRec: tObjRec;
...
procedure GetFieldsNames;
...
public
...
procedure SetRec (aRec: Pointer);
...
published
...
constructor Create (aOwner: tComponent);
...
end;
implementation
constructor tRttiHelperClass.Create (aOwner: tComponent);
begin
fCtxt := tRttiContext.Create;
end;
procedure tRttiHelperClass.SetRec (aRec: Pointer);
begin
private
fObjectRec.Rec := aRec;
procedure GetFieldsNames;
end;
procedure tRttiHelperClass.GetFieldsNames;
var f : Word ;
fields : tRttiType;
begin
with fRttiContext do begin
RttiType := GetType (fObjRec.ClassType);
Fields := RttiType.GetFields;
for f := Low (fields) to High (fields) fo begin
if fields[f].GetValue (tObject (fObjRec^)).IsArray then // this works
...
if fields[f].GetValue (tObject (fObjRec^)).IsObject then // this works
...
if fields[f].GetValue (tObject (fObjRec^)).IsRecord then // "undeclared identifier IsRecord"
...
end;
end;
end.
我知道为了使用Records,我必须使用tRttiRecordType,但我找不到正确的方法来执行此操作。如何确定某个字段是否为记录的正确代码? 感谢。
答案 0 :(得分:2)
请改为尝试:
if fields[f].FieldType.IsRecord then
来自System.Rtti.TRttiField.FieldType和System.Rtti.TRttiType.IsRecord。
现在,这里的根本问题是您无法从无类型指针解析记录字段。为了做类似的事情,将你的记录作为TValue传递。
procedure SetRec( aRec: TValue);
这样称呼:
SetRec(TValue.From(MyRec));
有关如何执行此操作并解析记录内容的更完整教程,请参阅Convert Record to Serialized Form Data for sending via HTTP。
传递TValue也适用于类和其他类型。