鉴于某人说Delphi的反射不能传入或传出类,我在此纠正一下这个说法,下面的代码可以证实,类可以传入传出。
由于我已经把D2009的反射单元移去D2007,因此就不用D2009了,所以代码中暂时不考虑Unicode的问题。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ObjAutoX, StdCtrls;
type
{$MethodInfo ON}
TTest=class(TPersistent)
public
procedure Call(s: string; AForm: TForm);
function Call2(s: string): TComponent;
end;
{$MethodInfo OFF}
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
t: TTest;
mih : PMethodInfoHeader;
begin
t := TTest.Create;
mih := GetMethodInfo(t, 'Call');
ObjectInvoke(t, mih, [1,2], ['222',Integer(self)]);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
t: TTest;
mih : PMethodInfoHeader;
ret: Integer;
begin
t := TTest.Create;
mih := GetMethodInfo(t, 'Call2');
ret:=ObjectInvoke(t, mih, [1,2], ['button1']);
TButton(ret).Caption := '222';
end;
{ TTest }
procedure TTest.Call(s: string; AForm: TForm);
begin
ShowMessage(s+':'+AForm.Caption);
end;
function TTest.Call2(s: string): TComponent;
begin
Result := form1.FindComponent(s);
end;
end.
由于我已经把D2009的反射单元移去D2007,因此就不用D2009了,所以代码中暂时不考虑Unicode的问题。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ObjAutoX, StdCtrls;
type
{$MethodInfo ON}
TTest=class(TPersistent)
public
procedure Call(s: string; AForm: TForm);
function Call2(s: string): TComponent;
end;
{$MethodInfo OFF}
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
t: TTest;
mih : PMethodInfoHeader;
begin
t := TTest.Create;
mih := GetMethodInfo(t, 'Call');
ObjectInvoke(t, mih, [1,2], ['222',Integer(self)]);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
t: TTest;
mih : PMethodInfoHeader;
ret: Integer;
begin
t := TTest.Create;
mih := GetMethodInfo(t, 'Call2');
ret:=ObjectInvoke(t, mih, [1,2], ['button1']);
TButton(ret).Caption := '222';
end;
{ TTest }
procedure TTest.Call(s: string; AForm: TForm);
begin
ShowMessage(s+':'+AForm.Caption);
end;
function TTest.Call2(s: string): TComponent;
begin
Result := form1.FindComponent(s);
end;
end.