W
wind_2005
Unregistered / Unconfirmed
GUEST, unregistred user!
我写了如下一段代码,在procedure TForm1.Button1Click(Sender: TObject);的最后一句报异常,该语句是想实现:将一对象函数(of object)赋给普通函数指针,并调用该对象函数。请问各们,如何实现上述功?先在这里谢谢大家了!unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TFunctionType = function: string of object
//定义对象函数指针 TFunctionType1 = function: string
//定义函数指针 TForm1 = class(TForm) Button1: TButton
procedure Button1Click(Sender: TObject)
private { Private declarations } function selfFunciotn: string
public { Public declarations } end;var Form1: TForm1;procedure CallFunction(ft: TFunctionType)
//以函数指针为参数,调用指定函数procedure CallFunction1(ft: TFunctionType1)
//以函数指针为参数,调用指定函数function GFunction(obj: TObject): string;function GFunction1(): string;implementation{$R *.dfm}//以对象函数指针为参数,过程中调用传入函数procedure CallFunction(ft: TFunctionType);begin ShowMessage(ft);end;//以普通函数指针为参数,过程中调用传入函数procedure CallFunction1(ft: TFunctionType1);begin ShowMessage(ft);end;//普通函数,多了一个参数,用以与 对象函数指针 兼容function GFunction(obj: TObject): string;begin Result:= 'GFunction';end;//普通函数function GFunction1(): string;begin Result:= 'GFunction1';end;procedure TForm1.Button1Click(Sender: TObject);var M: TMethod;begin //以对象函数指针为参数,调用普通函数,成功 M.Code := @GFunction
M.Data := nil
CallFunction(TFunctionType(M))
//以对象函数指针为参数,调用对象函数,成功 CallFunction(self.selfFunciotn)
//以普通函数指针为参数,调用普通函数,成功 CallFunction1(GFunction1)
//以普通函数指针为参数,调用对象函数,失败 CallFunction1(MethodAddress('selfFunciotn'));end;function TForm1.selfFunciotn: string;begin Result:= 'selfFunciotn';end;end.
//定义对象函数指针 TFunctionType1 = function: string
//定义函数指针 TForm1 = class(TForm) Button1: TButton
procedure Button1Click(Sender: TObject)
private { Private declarations } function selfFunciotn: string
public { Public declarations } end;var Form1: TForm1;procedure CallFunction(ft: TFunctionType)
//以函数指针为参数,调用指定函数procedure CallFunction1(ft: TFunctionType1)
//以函数指针为参数,调用指定函数function GFunction(obj: TObject): string;function GFunction1(): string;implementation{$R *.dfm}//以对象函数指针为参数,过程中调用传入函数procedure CallFunction(ft: TFunctionType);begin ShowMessage(ft);end;//以普通函数指针为参数,过程中调用传入函数procedure CallFunction1(ft: TFunctionType1);begin ShowMessage(ft);end;//普通函数,多了一个参数,用以与 对象函数指针 兼容function GFunction(obj: TObject): string;begin Result:= 'GFunction';end;//普通函数function GFunction1(): string;begin Result:= 'GFunction1';end;procedure TForm1.Button1Click(Sender: TObject);var M: TMethod;begin //以对象函数指针为参数,调用普通函数,成功 M.Code := @GFunction
M.Data := nil
CallFunction(TFunctionType(M))
//以对象函数指针为参数,调用对象函数,成功 CallFunction(self.selfFunciotn)
//以普通函数指针为参数,调用普通函数,成功 CallFunction1(GFunction1)
//以普通函数指针为参数,调用对象函数,失败 CallFunction1(MethodAddress('selfFunciotn'));end;function TForm1.selfFunciotn: string;begin Result:= 'selfFunciotn';end;end.