包含如下的六个部分:
Anonymous Event Handlers
Timing Anonymous Methods 计时功能匿名方法
Thread Synchronization with the
VCL
Parallel For Loop
AJAX in Delphi
Debating the AJAX Demo AJAX应用的辩论
匿名事件处理器
早期时候,Delphi有一个很特别的特性,就是可以用方法指针实现事件处理器。现在使用更高级的匿名方法,更加有效使用这个特性,可以绑定一个新的行为到一个事件,优点是:
- type
-
TAnonNotif = reference to procedure (Sender: TObject); -
// interceptor class -
TButton = class (StdCtrls .TButton) -
private -
FAnonClick: TAnonNotif; -
procedure SetAnonClick( constValue: TAnonNotif); -
public -
procedure Click; override; -
public -
property AnonClick: TAnonNotif -
read FAnonClick write SetAnonClick; -
end;
这个类的代码很容易理解,setter方法保存新的指针,Click方法在处理标准过程之前调用它(当可用时,调用OnClick事件处理)。
- procedure
TButton .SetAnonClick(constValue: TAnonNotif); -
begin -
FAnonClick := Value; -
end;
- procedure
TButton .Click; -
begin -
if Assigned then(FAnonClick) -
FAnonClick (self) -
inherited; -
end;
- procedure
TFormAnonButton .btnAssignClick( -
Sender:
TObject); -
begin -
btnInvoke.AnonClick := -
procedure (Sender: TObject) -
begin -
ShowMessage ((Sender as TButton).Caption); -
end; -
end
似乎这样使用没有意义,因为可以使用通常方法达到这个效果。下面,为了显示不同,用匿名方法捕获一个组件指针,这个组件的指针指定了一个事件处理函数,通过Sender的指向参数。
可以临时指定一个局部变量,作为Sender匿名方法的参数,隐藏btnKeepRefClick方法的Sender参数:
- procedure
TFormAnonButton .btnKeepRefClick( -
Sender:
TObject); -
var -
aCompRef: TComponent; -
begin -
aCompRef := Sender as TComponent; -
btnInvoke.AnonClick := -
procedure (Sender: TObject) -
begin -
ShowMessage ((Sender as TButton).Caption + -
' assigned by ' + .Name);aCompRef -
end; -
end;
- procedure
TFormAnonButton .FormMouseDown( -
Sender:
TObject; Button: TMouseButton; -
Shift:
TShiftState; X, Y: Integer); - begin
- if
Button then= mbLeft - btnLeftInvokeForm.AnonClick
:= - procedure
(Sender: TObject) - begin
- (Sender
as TButton).Caption := - 'Last
left on [' + IntToStr (X) + - ','
+ ']';IntToStr (Y) + - end
- else
- btnRightInvokeForm.AnonClick
:= - procedure
(Sender: TObject) - begin
- (Sender
as TButton).Caption := - 'Last
right on [' + IntToStr (X) + - ','
+ ']';IntToStr (Y) + - end;
- end;
这是另一个捕获执行上下文的例子,但是这次同时有两个捕获操作(每一个的数据都保持在内存),并且可以处理更多。为了使用方法指针实现相同的操作,你必须保持一个鼠标点击数组,捆绑到每一个目标组件,或者使用组件的Tag属性保存指针信息。