delphi - 如何使用 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);
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.FieldTypeSystem.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/

相关文章:

delphi - 通用整数的奇怪 PTypeInfo 名称

delphi - 我可以在一个单元中定义条件并在其他单元中使用它们吗?

Delphi/ASM 代码与 64 位不兼容?

delphi - 如何获取方法指针指向的方法的名称?

delphi - 动态创建组件时如何强制VCL样式覆盖?

delphi - 如何在不使用 COM 自动化的情况下处理 Word 文档?

c++ - 使用 std::type_index 作为映射中的值

delphi - 使用 TValue 将字符串转换为枚举类型?

delphi - 列表中的对象需要访问父列表属性

Delphi Protocol Buffer ?