Anonymous method as function result

。_饼干妹妹 提交于 2019-12-10 21:04:46

问题


What I want to do is to assign an anonymous method which I get as a function result to a variable of the same type. Delphi complains about not beeing able to do the assignement. Obviously Delphi things I want to assign the "GetListener" function instead of the result of that same function. Any help with this is very 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; 

回答1:


Use the following syntax:

  Listener:= MyClass.GetListener();

I have written the following example to make clear the difference between the MyClass.GetListener() and MyClass.GetListener assignments:

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;



回答2:


The only way I've found to work around this is to declare your GetListener like this:

procedure GetListener(var a: TPropertyChangedListener);

There might be some syntax to force the compiler to consider the function's result instead of the function itself, but I couldn't find any.



来源:https://stackoverflow.com/questions/2788424/anonymous-method-as-function-result

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