Passing procedure as a parameter in Delphi [closed]

痴心易碎 提交于 2020-03-26 04:52:05

问题


I have this code >

type
  TCallBack = procedure(APerc: Integer) of object;

....

procedure CallingProcedure(a, b, c: Integer; ACallBack: TCallBack = nil);

....

I call this function from my main class/object like this:

CallingProcedure(1, 2, 3, DoOnCallBack);

where DoOnCallBack is defined as:

procedure DoOnCallBack(APerc: Integer);

This compiles good, it's not problem - I did this tons of times.

But in CallingProcedure when I want to check if Assigned(ACallBack) I'm getting False.

Can someone tell me what I'm doing wrong.

I'm calling this from Thread, is that might be a problem?


回答1:


I makes no diffrence from where you call it. The syntax is the same. I've just made this small test example :

type
  TCallBack = procedure(APerc: Integer) of object;
  TForm20 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    procedure CallingProcedure(a, b, c: Integer; ACallBack: TCallBack = nil);
    procedure DoOnCallBack(APerc: Integer);
  public
    { Public declarations }
  end;

var
  Form20: TForm20;

implementation

{$R *.dfm}

procedure TForm20.CallingProcedure(a, b, c: Integer; ACallBack: TCallBack);
begin
  if Assigned(ACallBack) then
    ACallBack(a);
end;

procedure TForm20.DoOnCallBack(APerc: Integer);
begin
  ShowMessage(IntToStr(APerc));
end;

procedure TForm20.FormCreate(Sender: TObject);
begin
  CallingProcedure(1, 2, 3, DoOnCallBack);
  CallingProcedure(1, 2, 3, nil);
end;

And it works just fine. Ajust you code to look like this. Since you haven't posted your real code I can only guess what the problem is.



来源:https://stackoverflow.com/questions/30337521/passing-procedure-as-a-parameter-in-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!