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:
我正在寻找将对象的方法传递给过程的最简单方法,以便过程可以调用对象的方法(例如,在超时之后,或者可能在不同的线程中)。所以基本上我想:
- Capture a reference to an object's method.
- Pass that reference to a procedure.
- Using that reference, call the object's method from the procedure.
捕获对象方法的引用。
将该引用传递给过程。
使用该引用,从过程中调用对象的方法。
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.)
(一旦问题得到解答,我将删除上述代码,除非它以某种方式帮助解释。)
2 个解决方案
#1
18
Just remove the Pointer stuff. Delphi will do it for you:
只需删除Pointer的东西。德尔福会为您做到:
procedure TCallbackObject.SetupCallback;
begin
CallbackTheCallback(CallbackMethodImpl);
end;
#2
2
The reason you don't need the pointer syntax is that you've declared the method type as a procedure of object. The compiler will figure out from the "of object" statement how to handle passing the method off the callback proc.
您不需要指针语法的原因是您已将方法类型声明为对象的过程。编译器将从“of object”语句中弄清楚如何处理从回调proc传递方法。
#1
18
Just remove the Pointer stuff. Delphi will do it for you:
只需删除Pointer的东西。德尔福会为您做到:
procedure TCallbackObject.SetupCallback;
begin
CallbackTheCallback(CallbackMethodImpl);
end;
#2
2
The reason you don't need the pointer syntax is that you've declared the method type as a procedure of object. The compiler will figure out from the "of object" statement how to handle passing the method off the callback proc.
您不需要指针语法的原因是您已将方法类型声明为对象的过程。编译器将从“of object”语句中弄清楚如何处理从回调proc传递方法。