如何传递一个对象方法作为参数在Delphi,然后调用它? [英] How to Pass an Object Method as a Parameter in Delphi, and then Call It?
问题描述
我恐怕这可能是一个虚假的问题,但它有我很累的。
I fear this is probably a bit of a dummy question, but it has me pretty stumped.
我正在寻找最简单的方法可能传递一个方法的对象到过程中,以便过程可以调用对象的方法(例如在超时后,或者可能在不同的线程中)。所以基本上我想:
I'm looking for the simplest way possible to pass a method of an object into a procedure, so that the procedure can call the object's method (e.g. after a timeout, or maybe in a different thread). So basically I want to:
- 捕获对象方法的引用。
我想我可以使用接口实现相同的效果,但我认为有另一种方式,因为这个对象的过程类型声明存在。
I figure I could achieve the same effect using interfaces, but I thought there was another way, since this "procedure of object" type declaration exists.
以下不会工作,但可能有助于解释我感到困惑...?
The following doesn't work, but might it help explain where I'm confused...?
interface
TCallbackMethod = procedure of object;
TCallbackObject = class
procedure CallbackMethodImpl;
procedure SetupCallback;
end;
implementation
procedure CallbackTheCallback(const callbackMethod: TCallbackMethod);
begin
callbackMethod();
end;
procedure TCallbackObject.CallbackMethodImpl;
begin
// Do whatever.
end;
procedure TCallbackObject.SetupCallback;
begin
// following line doesn't compile - it fails with "E2036 Variable required"
CallbackTheCallback(@self.CallbackMethodImpl);
end;
(一旦问题得到解答,我将删除上述代码,除非它有助于解释。
(Once the question is answered I'll remove the above code unless it aids the explanation somehow.)
推荐答案
只需删除指针内容即可。 Delphi会为你做:
Just remove the Pointer stuff. Delphi will do it for you:
procedure TCallbackObject.SetupCallback;
begin
CallbackTheCallback(CallbackMethodImpl);
end;
这篇关于如何传递一个对象方法作为参数在Delphi,然后调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!