Anonymous method as a result of a function

What I want to do is assign an anonymous method, which I get as the result of a function for a variable of the same type. Delphi complains that she will not be able to complete the task. Obviously, with Delphi stuff, I want to assign a GetListener function instead of the result of the same function. Any help with this is much appreciated.

type TPropertyChangedListener = reference to procedure (Sender: TStimulus); TMyClass = class function GetListener:TPropertyChangedListener end; .... var MyClass: TMyClass; Listener: TPropertyChangedListener; begin MyClass:= TMyClass.create; Listener:= MyClass.GetListener; // Delphi compile error: E2010 Incompatible types: TPropertyChangedListener' and 'Procedure of object' end; 
+3
anonymous-methods delphi delphi-2009
source share
2 answers

Use the following syntax:

  Listener:= MyClass.GetListener(); 

I wrote the following example to clarify the difference between the assignments of MyClass.GetListener () and MyClass.GetListener:

 type TProcRef = reference to procedure(Sender: TObject); TFunc = function: TProcRef of object; TMyClass = class function GetListener: TProcRef; end; function TMyClass.GetListener: TProcRef; begin Result:= procedure(Sender: TObject) begin Sender.Free; end; end; procedure TForm1.Button1Click(Sender: TObject); var MyClass: TMyClass; ProcRef: TProcRef; Func: TFunc; begin MyClass:= TMyClass.Create; // standard syntax ProcRef:= MyClass.GetListener(); // also possible syntax // Func:= MyClass.GetListener; // ProcRef:= Func(); ProcRef(MyClass); end; 
+11
source share

The only way I found work with is to declare your GetListener as follows:

 procedure GetListener(var a: TPropertyChangedListener); 

There may be some syntax to force the compiler to consider the result of the function instead of the function itself, but I could not find it.

0
source share

All Articles