Delphi 2010新機能之:Rttiユニット(2)

2346 ワード

また、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.


 
   

列挙値の設定方法:


procedure TForm1.Button3Click(Sender: TObject);

var

  t: TRttiType;

  p: TRttiProperty;

  r: TValue;

begin

  t := TRttiContext.Create.GetType(TButton);



  p := t.GetProperty('Align');

  p.SetValue(Button1, TValue.FromOrdinal(TypeInfo(TAlign), Ord(alLeft)));



  r := p.GetValue(Button1);

  ShowMessage(IntToStr(r.AsOrdinal)); {3}

end;