简体   繁体   English

Delphi:如何将Click事件分配给对象的方法?

[英]Delphi: How to assign Click event to object's method?

i have a menu item, and i'm trying to assign its OnClick event handler: 我有一个菜单项,并且我正在尝试分配其OnClick事件处理程序:

miFrobGizmo.OnClick := {something};

The OnClick event handler property, like almost every other event handler, is defined as a TNotifyEvent method type: 与几乎所有其他事件处理程序一样, OnClick事件处理程序属性被定义为TNotifyEvent方法类型:

property OnClick: TNotifyEvent 

where TNotifyEvent is: 其中TNotifyEvent为:

TNotifyEvent = procedure(Sender: TObject) of object;

i have an object, with a method matching the TNotifyEvent signature: 我有一个对象,其方法与TNotifyEvent签名匹配:

TAnimal = class(TObject)
public
   procedure Frob(Sender: TObject);
end;

So i think i should be able to take the method of the object and assign it to the click event handler: 所以我认为我应该能够采用该对象的方法并将其分配给click事件处理程序:

var
   Animal: TAnimal;


miFrobGizmo.OnClick := Animal.Frob;

Except i get the error: 除非我得到错误:

[Error]File.pas(1234): Not enough actual parameters

Perhaps i'm having a brain fart, but i thought i should be able to do this. 也许我正在放屁,但我认为我应该能够做到这一点。


A detail i failed to mention is that my object that has the matching method is having the method exposed though an interface: 我未能提及的一个细节是,具有匹配方法的对象正在通过接口公开该方法:

IAnimal = interface
   procedure Frob(Sender: TObject);
end;

TAnimal = class(TInterfacedObject, IAnimal)
public
   procedure Frob(Sender: TObject);
end;

var
   Animal: IAnimal;

miFrobGizmo.OnClick := Animal.Frob;

Follow-up question 后续问题

If this won't work, what will? 如果这不起作用,那会怎样?

You can't do that. 你不能那样做。 It says "procedure of object", not "procedure of interface". 它说的是“对象的过程”,而不是“接口的过程”。 It would let you do that if you were using an object directly, but since you're not, it doesn't consider that you're trying to assign the event handler and instead the parser tries to treat your code as a method call. 如果您直接使用一个对象,它将使您做到这一点,但是由于您没有使用它,因此它不会认为您正在尝试分配事件处理程序,而是解析器尝试将您的代码视为方法调用。 Then it sees that you don't have any parameters for your method call, but the call requires one parameter so it gives up and gives you an error message. 然后,它会看到您的方法调用没有任何参数,但是该调用需要一个参数,因此它放弃并给您一条错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM