First we??™ll see examples of anonymous
methods that take parameters but don??™t return any values; then we??™ll explore the
syntax involved in providing return values and a shortcut available when we don??™t
need to use the parameters passed to us.
5.4.1 Starting simply: acting on a parameter
In chapter 3 we saw the Action
delegate type. As a reminder, its signature is very
simple (aside from the fact that it??™s generic):
public delegate void Action(T obj)
In other words, an Action does something with an instance of T. So an
Action could reverse the string and print it out, an Action could print
out the square root of the number passed to it, and an Action> could
find the average of all the numbers given to it and print that out. By complete coincidence,
these examples are all implemented using anonymous methods in listing 5.5.
Action printReverse = delegate(string text)
{
char[] chars = text.ToCharArray();
Array.Reverse(chars);
Console.WriteLine(new string(chars));
};
Action printRoot = delegate(int number)
{
Console.WriteLine(Math.Sqrt(number));
};
Action> printMean = delegate(IList numbers)
{
double total = 0;
foreach (double value in numbers)
{
total += value;
}
Console.WriteLine(total/numbers.Count);
};
double[] samples = {1.5, 2.5, 3, 4.5};
Listing 5.
Pages:
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300