通過 Rtti 單元的 TRttiContext(是個 record), 可以方便地獲取類的方法、屬性、字段的列表.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Rtti;
//TRttiContext.GetTypes
procedure TForm1.Button1Click(Sender: TObject);
var
ctx: TRttiContext;
t: TRttiType;
begin
Memo1.Clear;
for t in ctx.GetTypes do Memo1.Lines.Add(t.Name);
end;
//獲取 TButton 類的方法
procedure TForm1.Button2Click(Sender: TObject);
var
ctx: TRttiContext;
t: TRttiType;
m: TRttiMethod;
begin
Memo1.Clear;
t := ctx.GetType(TButton);
//for m in t.GetMethods do Memo1.Lines.Add(m.Name);
for m in t.GetMethods do Memo1.Lines.Add(m.ToString);
end;
//獲取 TButton 類的屬性
procedure TForm1.Button3Click(Sender: TObject);
var
ctx: TRttiContext;
t: TRttiType;
p: TRttiProperty;
begin
Memo1.Clear;
t := ctx.GetType(TButton);
//for p in t.GetPropertIEs do Memo1.Lines.Add(p.Name);
for p in t.GetPropertIEs do Memo1.Lines.Add(p.ToString);
end;
//獲取 TButton 類的字段
procedure TForm1.Button4Click(Sender: TObject);
var
ctx: TRttiContext;
t: TRttiType;
f: TRttiFIEld;
begin
Memo1.Clear;
t := ctx.GetType(TButton);
//for f in t.GetFIElds do Memo1.Lines.Add(f.Name);
for f in t.GetFIElds do Memo1.Lines.Add(f.ToString);
end;
//獲取獲取 TButton 類的方法集合、屬性集合、字段集合
procedure TForm1.Button5Click(Sender: TObject);
var
ctx: TRttiContext;
t: TRttiType;
ms: TArray<TRttiMethod>;
ps: TArray<TRttiProperty>;
fs: TArray<TRttiFIEld>;
begin
Memo1.Clear;
t := ctx.GetType(TButton);
ms := t.GetMethods;
ps := t.GetPropertIEs;
fs := t.GetFIElds;
Memo1.Lines.Add(Format('%s 類共有 %d 個方法', [t.Name, Length(ms)]));
Memo1.Lines.Add(Format('%s 類共有 %d 個屬性', [t.Name, Length(ps)]));
Memo1.Lines.Add(Format('%s 類共有 %d 個字段', [t.Name, Length(fs)]));
end;
end.