鉴于某人说Delphi的反射不能传入或传出类,我在此纠正一下这个说法,下面的代码可以证实,类可以传入传出。
3
4
9
11
由于我已经把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.
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.
网友评论:
2
奇怪了,偶有想过Integer的,但是貌似报错,我再看看。 对了,出错的情况是,我给对象类型的参数加了var或者out,这样好像就不行了。 返回值是对象的话,貌似也是不行的,您可以试试看(Variant的类型成了varError)。偶也再试试。不用var、out尚可,不能返回对象还是白搭。
“下面的代码可以证实,类可以传入传出” ====================== 您这个只是对象里面的属性值传入传出,因此只要能“传入”,必然能”传出”。 偶理解的对象传入传出是指对象的引用的传入传出,就像偶说的加var、out的那种。
==,看错了,貌似真的是返回了对象。莫非要您修改过的那个单元才可以?偶之前试验确实不行,偶再试试看 - -....
还真的是,用D7那个OBJINVOKE,这么用法是会出错的(提示参数类型不匹配),但是用你放出来的那个单元就不会。
“肥猫你真早。。。” 嗯,俗话有说:“早起的猫儿有橙吃”