Delphi 如何使用Rtti确定类中的字段是否为记录
我编写了一个RttiHelper类,它可以检索类的所有字段名。该过程成功地确定字段是对象还是数组,但无法确定字段是记录。代码如下:Delphi 如何使用Rtti确定类中的字段是否为记录,delphi,delphi-xe2,rtti,Delphi,Delphi Xe2,Rtti,我编写了一个RttiHelper类,它可以检索类的所有字段名。该过程成功地确定字段是对象还是数组,但无法确定字段是记录。代码如下: unit Form1 interface uses RttiHelper; type tMyRec = Record ... end; ... implementation var MyRec : tMyRec; procedure FormCreate (Sender: tObject); begin SetRec (@MyRec);
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.
我知道为了处理记录,我必须使用tRttiRecordType,但我找不到正确的方法。如何确定某个字段是否为记录的正确代码?
谢谢。试试这个:
if fields[f].FieldType.IsRecord then
来自和
现在,这里的根本问题是无法从非类型指针解析记录字段。要执行类似操作,请将记录作为TValue传递
procedure SetRec( aRec: TValue);
可以这样说:
SetRec(TValue.From(MyRec));
有关如何执行此操作并解析记录内容的更完整教程,请参见
传递TValue也适用于类和其他类型。我已经尝试过了,但是由于字段[f]实际上是指针,它返回一个
tkPointer
。必须有一种方法来检查字段[f]指向的记录。啊,误读了这个问题。这样的记录没有可用的RTTI。必须将记录类型传递给助手。