Delphi中有没有一种方法可以将匿名方法分配给按钮事件? [英] Is there a way in Delphi to assign an anonymous method to a button event?
问题描述
我想知道Delphi中是否有一种方法可以将匿名方法分配给表单控件事件.
I was wondering if there is a way in Delphi to assign an anonymous method to a form control event.
例如:
Button1.OnClick := procedure (Sender: TObject) begin ShowMessage('') end;
当然,这给了我一个错误
Of course this gives me an error
[dcc32错误] Control.Controller.pas(51):E2009不兼容的类型:方法指针和常规过程"
[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
推荐答案
这是不可能的.您必须使事件处理程序成为方法类型,而不是匿名方法.
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
这篇关于Delphi中有没有一种方法可以将匿名方法分配给按钮事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!