如何检查两个事件是否指向 Delphi 中的同一过程? [英] How to check if two events are pointing to the same procedure in Delphi?

查看:25
本文介绍了如何检查两个事件是否指向 Delphi 中的同一过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个链接到 Button1Click 过程的 Button1.OnClick 事件.我也有 Button2.OnClick 链接到其他一些程序.如何从运行时检查两个事件是否链接到不同或相同的过程?

Say I have a Button1.OnClick event linked to Button1Click procedure. I also have Button2.OnClick linked to some other procedure. How do I check that both events are linked to different or same procedure from runtime?

我尝试测试是否:

  • Button1.OnClick = Button2.OnClick,但这给了我一个错误(没有足够的实际参数)
  • @(Button1.OnClick) = @(Button2.OnClick),又报错(实际参数不够)

如何正确测试?

推荐答案

方法引用可以分解为两部分,指向对象的指针和指向方法本身的指针.在 System 单元中定义了一个方便的记录类型,称为 TMethod,它允许我们进行分解.

A method reference can be broken down in to two parts, the pointer to the object and the pointer to the method itself. There is a convenient record type defined in the System unit called TMethod that allows us to do that break down.

有了这些知识,我们可以写出这样的东西:

With that knowledge, we can write something like this:

function SameMethod(AMethod1, AMethod2: TNotifyEvent): boolean;
begin
  result := (TMethod(AMethod1).Code = TMethod(AMethod2).Code) 
            and (TMethod(AMethod1).Data = TMethod(AMethod2).Data);   
end;

希望这会有所帮助.:)

Hope this helps. :)

编辑:只是为了以更好的格式列出我在这里尝试解决的问题(如评论中所提到的).

Edit: Just to lay out in a better format the problem I am trying to solve here (as alluded to in the comments).

如果你有两个表单,都从同一个基类实例化:

If you have two forms, both instantiated from the same base class:

Form1 := TMyForm.Create(nil);
Form2 := TMyForm.Create(nil);

并且您将这些表单中的相同方法分配给两个按钮:

and you assign the same method from those forms to the two buttons:

Button1.OnClick := Form1.ButtonClick;
Button2.OnClick := Form2.ButtonClick;

并且比较两个OnClick属性,你会发现Code是一样的,但是Data是不同的.那是因为它是相同的方法,但是在类的两个不同实例上...

And compare the two OnClick properties, you will find that the Code is the same, but the Data is different. That is because it's the same method, but on two different instantiations of the class...

现在,如果你在同一个对象上有两个方法:

Now, if you had two methods on the same object:

Form1 := TMyForm.Create(nil);

Button1.OnClick := Form1.ButtonClick1;
Button2.OnClick := Form1.ButtonClick2;

那么他们的Data会是一样的,但是他们的Code会不同.

Then their Data will be the same, but their Code will be different.

这篇关于如何检查两个事件是否指向 Delphi 中的同一过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆