Delphi:测试事件处理程序分配 [英] Delphi: Test event handler assignment

查看:120
本文介绍了Delphi:测试事件处理程序分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在构造函数中分配一个事件处理程序,如果它没有一个分配。因此,我想删除析构函数中最终分配的事件处理程序。我写的代码如下,但不能编译。

I want to assign an event handler in constructor, if it does not have one assigned. Consequentially I want to remove the eventually assigned event handler in destructor. I wrote the code as follows, but cannot be compiled.

constructor TSomeControl.Create(Panel: TPanel);
begin
  inherited Create;
  FPanel := Panel;
  if not Assigned(FPanel.OnResize) then
    FPanel.OnResize := HandlePanelResize;
end;

destructor TSomeControl.Destroy;
begin
  if @FPanel.OnResize = @HandlePanelResize then // [dcc32 Error] E2036 Variable required
    FPanel.OnResize := nil;
  FPanel := nil;
  inherited;
end;

如何正确测试?我知道一个解决方案是使用变量进行记录,无论我是否已经分配了 OnResize 。但是我不希望这是解决方案。

How to test it properly? I know a solution is to use a variable to record, whether I have assigned OnResize. But I do not want this as solution.

推荐答案

不需要在这里编写任何自定义代码,因为您可以使用已经存在的compare从 Generics.Defaults

No need to write any custom code here as you can use the already existing comparers from Generics.Defaults:

destructor TSomeControl.Destroy;
begin
  if Assigned(FPanel) and TEqualityComparer<TNotifyEvent>.Default.Equals(
    FPanel.OnResize, HandlePanelResize) then
    FPanel.OnResize := nil;
  FPanel := nil;
  inherited;
end;

这篇关于Delphi:测试事件处理程序分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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