【发布时间】:2011-12-22 22:52:41
【问题描述】:
由于匿名方法出现在 Delphi 中,我想在 VCL 组件事件中使用它们。显然,为了向后兼容,VCL 没有更新,所以我设法做了一个简单的实现,但有一些注意事项。
type
TNotifyEventDispatcher = class(TComponent)
protected
FClosure: TProc<TObject>;
procedure OnNotifyEvent(Sender: TObject);
public
class function Create(Owner: TComponent; const Closure: TProc<TObject>): TNotifyEvent; overload;
function Attach(const Closure: TProc<TObject>): TNotifyEvent;
end;
implementation
class function TNotifyEventDispatcher.Create(Owner: TComponent; const Closure: TProc<TObject>): TNotifyEvent;
begin
Result := TNotifyEventDispatcher.Create(Owner).Attach(Closure)
end;
function TNotifyEventDispatcher.Attach(const Closure: TProc<TObject>): TNotifyEvent;
begin
FClosure := Closure;
Result := Self.OnNotifyEvent
end;
procedure TNotifyEventDispatcher.OnNotifyEvent(Sender: TObject);
begin
if Assigned(FClosure) then
FClosure(Sender)
end;
end.
这就是它的用法,例如:
procedure TForm1.FormCreate(Sender: TObject);
begin
Button1.OnClick := TNotifyEventDispatcher.Create(Self,
procedure (Sender: TObject)
begin
Self.Caption := 'DONE!'
end)
end;
我相信很简单,有两个缺点:
我必须创建一个组件来管理匿名方法的生命周期(我浪费了更多的内存,并且间接的速度有点慢,但我仍然更喜欢在我的应用程序中使用更清晰的代码)
我必须为每个事件签名实现一个新类(非常简单)。这个有点复杂,但 VCL 仍然有非常常见的事件签名,并且对于我创建类时的每个特殊情况,它都会永远完成。
你觉得这个实现怎么样?有什么可以让它变得更好?
【问题讨论】:
-
阅读问题和答案,我能看到的只是一个不存在的问题的解决方案。我认为尝试使用匿名方法只是将一组问题换成另一组问题。我在这里看不到任何胜利。
-
@DavidHeffernan:这就是解决方案的酷炫之处。
标签: delphi vcl anonymous-methods