In
this situation, the compiler throws its hands up and issues an error. You can solve this
either by specifying the parameter list explicitly or casting the anonymous method to the
right delegate type.
Hopefully what you??™ve seen of anonymous methods so far will have provoked
some thought about your own code, and made you consider where you could use
these techniques to good effect. Indeed, even if anonymous methods could only do
what we??™ve already seen, they??™d still be very useful. However, there??™s more to anonymous
methods than just avoiding the inclusion of an extra method in your code.
Anonymous methods are C# 2??™s implementation of a feature known elsewhere as closures
by way of captured variables. Our next section explains both of these terms and
shows how anonymous methods can be extremely powerful??”and confusing if you??™re
not careful.
5.5 Capturing variables in anonymous methods
I don??™t like having to give warnings, but I think it makes sense to include one here: if
this topic is new to you, then don??™t start this section until you??™re feeling reasonably
awake and have a bit of time to spend on it. I don??™t want to alarm you unnecessarily,
and you should feel confident that there??™s nothing so insanely complicated that you
won??™t be able to understand it with a little effort. It??™s just that captured variables can
be somewhat confusing to start with, partly because they overturn some of your existing
knowledge and intuition.
Pages:
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309