2017-07-03 66 views
2

我正在Delphi-Tokyo的Delphi-Tokyo學習RTTI來創建一個ORM,但我在訪問同時也是對象的屬性時遇到了問題。在下面的代碼中,我如何執行Prop的演員代碼爲id?在TRttiProperty實例如何爲對象執行TRTTIProperty的強制轉換

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. 

回答

2

呼叫GetValue,傳遞實例指針。這會產生一個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); 
相關問題