通過 Rtti 還能夠調用一個類的方法, 也能讀取或設置其屬性值.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
{自定義的類}
TMyClass = class(TComponent)
public
procedure msg(const str: string);
function Add(const a,b: Integer): Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Rtti;
{ MyClass 類的實現 -----------------------------------------------------------}
procedure TMyClass.msg(const str: string);
begin
MessageDlg(str, mtInformation, [mbYes], 0);
end;
function TMyClass.Add(const a, b: Integer): Integer;
begin
Result := a + b;
end;
//通過 Rtti 的手段使用 TMyClass 類的方法 --------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
obj: TMyClass;
t: TRttiType;
m1,m2: TRttiMethod;
r: TValue; //TRttiMethod.Invoke 的返回類型
begin
t := TRttiContext.Create.GetType(TMyClass);
{獲取 TMyClass 類的兩個方法}
m1 := t.GetMethod('msg'); {procedure}
m2 := t.GetMethod('Add'); {function}
obj := TMyClass.Create(Self); {調用需要依賴一個已存在的對象}
{調用 msg 過程}
m1.Invoke(obj, ['Delphi 2010']); {將彈出信息框}
{調用 Add 函數}
r := m2.Invoke(obj, [1, 2]); {其返回值是個 TValue 類型的結構}
ShowMessage(IntToStr(r.AsInteger)); {3}
obj.Free;
end;
//通過 Rtti 的手段修改並獲取 TMyClass 類的屬性 --------------------------------
procedure TForm1.Button2Click(Sender: TObject);
var
obj: TMyClass;
t: TRttiType;
p: TRttiProperty;
r: TValue;
begin
obj := TMyClass.Create(Self);
t := TRttiContext.Create.GetType(TMyClass);
p := t.GetProperty('Name');
p.SetValue(obj, 'NewName');
r := p.GetValue(obj);
ShowMessage(r.AsString); {NewName}
obj.Free;
end;
end.