我编写了一个 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.
我知道为了使用记录,我必须使用 tRttiRecordType,但我找不到正确的方法来执行此操作。确定某个字段是否为记录的正确代码是怎样的? 谢谢。
最佳答案
试试这个:
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 也适用于类和其他类型。
关于delphi - 如何使用 Rtti 确定类中的字段是否为记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26832540/