Delphi 回调函数

不是原创,原文链接: https://blog.csdn.net/u014028956/article/details/46810537

1、首先要声明一个类型;

        type  TProc = procedure(str:string) of object;     //这里的of object 一定要,不然会出错,也可能是有些方法自己不知道吧,希望知道的可以告诉一声;

2、定义一个过程

procedure test(str:string);    //注意这个作为参数的函数内部的参数必须和TProc 的参数一样;
begin
    showmessage(str);
end

3、定义一个调用test 这个函数的函数

procedure  dotest(F:TProc);
begin
   F('这是回调函数的测试');
end

4、 就可以使用了

procedure show();
begin
     dotest(test);
end

完整例子如下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,ComCtrls, StdCtrls;
 
type
  TFunc = procedure() of object;
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
   function myTest(f:TFunc):string;
   procedure abc();
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.abc;
begin
  showmessage('这是回调函数测试');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
   myTest(abc);
end;

function TForm1.myTest(f:TFunc):string;
begin
   f();
end;

end.

 

posted @ 2019-11-08 10:32  小党丶先生  阅读(465)  评论(0编辑  收藏  举报