Is there a way in Delphi to assign an anonymous method to a button event?

核能气质少年 提交于 2019-12-01 15:23:48

问题


I was wondering if there is a way in Delphi to assign an anonymous method to a form control event.

For example:

Button1.OnClick := procedure (Sender: TObject) begin ShowMessage('') end;

Of course this gives me an error

[dcc32 Error] Control.Controller.pas(51): E2009 Incompatible types: 'method pointer and regular procedure'

This is because the method must belong to an object, but then it would not be anonymous any more.

Perhaps there is some work around for this


回答1:


This is not possible. You have to make the event handler be a method type rather than an anonymous method.

You'll need to wrap your anonymous method in a method. Either an instance method (of a record or a class), or a class method. For instance:

  • VCL events with anonymous methods - what do you think about this implementation?
  • TProc<TObject> to TNotifyEvent


来源:https://stackoverflow.com/questions/25500770/is-there-a-way-in-delphi-to-assign-an-anonymous-method-to-a-button-event

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