delphi - 如何对对象执行 TRTTIProperty 的转换

标签 delphi rtti

我正在 Delphi-Tokyo 中学习 RTTI 以创建 ORM,但我在访问也是对象的属性时遇到问题。在下面的代码中,如何对 id 执行 Prop 的转换?

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, rtti, Vcl.StdCtrls;

type
  TIntField = class(TObject)
  private
    fDisplayNme: string;
  public
    constructor Create(DisplayName: string);
  published
    property DisplayName: string read fDisplayNme write fDisplayNme;
  end;

  TSale = class(TObject)
  private
    fIdSale: TIntField;
  public
    constructor Create;
  published
    property IdSale: TIntField read fIdSale write fIdSale;
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


{ TIntField }

constructor TIntField.Create(DisplayName: string);
begin
  fDisplayNme:= DisplayName;
end;

{ TSale }

constructor TSale.Create;
begin
  fIdSale:= TIntField.Create('idSale');
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Context: TRttiContext;
  TypObj:  TRttiType;
  Prop:    TRttiProperty;
  sale:    TSale;
  id:      TIntField;
begin
  sale:= TSale.Create;

  Context:= TRttiContext.Create;

  TypObj:= Context.GetType(sale.ClassInfo);

  prop:= TypObj.GetProperty('IdSale');

  id:= Prop as TIntField;  //Would you like to do this or something equivalent

  ShowMessage(id.DisplayName);
end;

end.

最佳答案

调用GetValue关于TRttiProperty实例,传递实例指针。这会产生 TValue您可以使用 AsType<T> 从中提取对象。像这样:

var
  Context: TRttiContext;
  Typ: TRttiType;
  Prop: TRttiProperty;
  sale: TSale;
  id: TIntField;
....
sale := TSale.Create;
Typ := Context.GetType(sale.ClassInfo);
Prop := Typ.GetProperty('IdSale');
id := Prop.GetValue(sale).AsType<TIntField>;
Writeln(id.DisplayName);

关于delphi - 如何对对象执行 TRTTIProperty 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885924/

相关文章:

Delphi 2010 RTTI 和接口(interface)字段

c++ - 使用 strip 会删除二进制文件上的 RTTI 信息吗?

delphi - 口音编码

delphi - Delphi XE4中不可勾选动态创建的TCheckBox

德尔福Rtti : how to get objects from TObjectList<T>

delphi - 在 Delphi 2010 中迭代索引属性

delphi - 重新引发异常的成本是多少?

delphi - 是否有 DCC32 选项将特定编译器警告视为错误?

delphi - 使用字符串形式的类名确定 Delphi 6 类对象是否是派生类?

c++ - vptr 是否曾经位于对象的开头?