您的位置:首页 > 编程语言 > Delphi

理解 Delphi 的类(十) - 深入方法[26] - 回调函数

2008-01-15 11:37 489 查看
//把一个方法当作另一个方法的参数, 就是回调方法, 大家习惯称作回调函数

type
TFunType = function(i: Integer): Integer; {声明一个方法类型}

function MyFun(i: Integer): Integer;        {建立类型兼容的函数}
begin
Result := i*2;
end;

{把函数当作参数, 再定义一个函数}
function MyTest(x: Integer; F: TFunType): Integer;
begin
Result := F(x);
end;

{测试}
procedure TForm1.Button1Click(Sender: TObject);
var
Fun: TFunType; {声明一个 TFunType 的变量}
i: Integer;
begin
Fun := MyFun;  {让方法变量 Fun 指向和它类型兼容的一个方法}

{测试 Fun; Fun 是一个方法变量, 现在去执行那个方法, 它就可以当作那个方法来使用了}
i := Fun(4);
ShowMessage(IntToStr(i));  //8

{把 Fun 当作参数使用; 把函数当作参数使用, 这就是回调函数}
i := MyTest(4,Fun);
ShowMessage(IntToStr(i));  //8
end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: