TProc< TObject>到TNotifyEvent [英] TProc<TObject> to TNotifyEvent

查看:521
本文介绍了TProc< TObject>到TNotifyEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了此帖子其接受的答案仍然非常神秘:

Further to this post whose accepted answer remains very cryptic:

@Button1.OnClick := pPointer(Cardinal(pPointer( procedure (sender: tObject) begin ((sender as TButton).Owner as TForm).Caption := 'Freedom to anonymous methods!' end )^ ) + $0C)^;

我想知道有可能设计出一种简单优雅的方式,类似于:

I wonder wether it is possible to devise a simplest and elegant way akin to:

Button.OnClick :=
                    AnonProc2NotifyEvent (
                    procedure (Sender: TObject)
                    begin
                      ((Sender as TButton).Owner as TForm).Caption := 'Freedom to anonymous methods!'
                    end
                      );

以达到相同的目的,而AnonProc2NotifyEvent是Button的所有者的方法,具有以下内容签名:

so as to attain the same purpose and where AnonProc2NotifyEvent is a method of the owner of Button with the following signature:

TOwnerOfButton = class(TForm)
  Button: TButton;
  ...
private
  ...
protected
  function AnonProc2NotifyEvent(aProc: TProc<TObject>): TNotifyEvent;
public
  ...
end;

是否可行,如果是这样实现?

Is that feasible and if so how to implement it ?

推荐答案

这将很容易做到这一点:

This will do the job readily enough:

type
  TNotifyEventWrapper = class(TComponent)
  private
    FProc: TProc<TObject>;
  public
    constructor Create(Owner: TComponent; Proc: TProc<TObject>);
  published
    procedure Event(Sender: TObject);
  end;

constructor TNotifyEventWrapper.Create(Owner: TComponent; Proc: TProc<TObject>);
begin
  inherited Create(Owner);
  FProc := Proc;
end;

procedure TNotifyEventWrapper.Event(Sender: TObject);
begin
  FProc(Sender);
end;

function AnonProc2NotifyEvent(Owner: TComponent; Proc: TProc<TObject>): TNotifyEvent;
begin
  Result := TNotifyEventWrapper.Create(Owner, Proc).Event;
end;

所有者参数c> AnonProc2NotifyEvent 使得可以管理包装器对象的生命周期。没有这样的东西,你会泄漏 TNotifyEventWrapper 的实例。

The Owner parameter in AnonProc2NotifyEvent is so that the lifetime of the wrapper object can be managed. Without something like that you would leak instances of TNotifyEventWrapper.

所有者身份传递所有者,连接事件的组件。例如:

Pass as Owner, the component to which you are connecting the event. For example:

Button1.OnClick := AnonProc2NotifyEvent(
  Button1,
  procedure(Sender: TObject)
  begin
    (Sender as TButton).Caption := 'Clicked';
  end
);

所以,当按钮被销毁时, TNotifyEventWrapper 也将被销毁。包装对象必须至少与其所关联事件的对象一样长。所以选择 Button1 作为所有者是自然和明显的。

So, when the button is destroyed, the TNotifyEventWrapper will also be destroyed. The wrapper object must live at least as long as the object to whose events it is associated. And so the choice of Button1 as the owner is the natural and obvious one.

这篇关于TProc&lt; TObject&gt;到TNotifyEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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