We??™ll see
that changes to the variable from outside the anonymous method are visible within
the anonymous method, and vice versa. We??™re using the ThreadStart delegate type
for simplicity as we don??™t need a return type or any parameters??”no extra threads are
actually created, though.
string captured = "before x is created";
ThreadStart x = delegate
{
Console.WriteLine(captured);
captured = "changed by x";
};
captured = "directly before x is invoked";
x();
Listing 5.11 Accessing a variable both inside and outside an anonymous method
Capture of
outer variable F
153 Capturing variables in anonymous methods
Console.WriteLine (captured);
captured = "before second invocation";
x();
The output of listing 5.11 is as follows:
directly before x is invoked
changed by x
before second invocation
Let??™s look at how this happens. First, we declare the variable captured and set its value
with a perfectly normal string literal. So far, there??™s nothing special about the variable.
We then declare x and set its value using an anonymous method that captures
captured. The delegate instance will always print out the current value of captured,
and then set it to ???changed by x???.
Just to make it absolutely clear that just creating the delegate instance didn??™t read
the variable and stash its value away somewhere, we now change the value of captured
to ???directly before x is invoked???.
Pages:
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313