Download objects

Transcript
15: Anonymous Methods - 313
The second button I added to the form for this specific step calls the anonymous
method stored in the AnonMeth property:
procedure TFormAnonymFirst.btnCallClick(Sender: TObject);
begin
if Assigned (AnonMeth) then
begin
CallTwice (2, AnonMeth);
end;
end;
When this code is executed, it calls an anonymous method that uses the local variable aNumber of a method that's not on the stack any more. However, since
anonymous methods capture their execution context the variable is still there and
can be used as long as that given instance of the anonymous method (that is, a reference to the method) is around.
As a further proof, do the following. Press the Store button once, the Call button
two times and you'll see that the same captured variable is being used:
5
8
10
13
note
The reason for this sequence is that the value starts at 3, each call to CallTwice passed its parameter to the anonymous methods a first time (that is 2) and then a second time after incrementing
it (that is, the second time it passes 3).
Now press Store once more and press Call again. What happens, why is the value of
the local variable reset? By assigning a new anonymous method instance, the old
anonymous method is deleted (along with its own execution context) and a new execution context is capture, including a new instance of the local variable. The full
sequence Store – Call – Call – Store – Call produces:
5
8
10
13
5
8
It is the implication of this behavior, resembling what some other languages do, that
makes anonymous methods an extremely powerful language feature, which you can
use to implement something that simply wasn't possible in the past.
Marco Cantù, Object Pascal Handbook