xiacy

导航

5.4.1 将匿名方法用于Action<T>委托类型

            Action<string> printReverse = delegate(string text)
            {
                char[] chars = text.ToCharArray();
                Array.Reverse(chars);
                Console.WriteLine(new string(chars));
            };

            Action<int> printRoot = delegate(int number)
            {
                Console.WriteLine(Math.Sqrt(number));
            };

            Action<IList<double>> printMean = delegate(IList<double> numbers)
            {
                double total = 0;
                foreach (double value in numbers)
                    total += value;
                Console.WriteLine(total / numbers.Count);
            };

            printReverse("Hello world!");
            printRoot(8);
            printMean(new double[] { 1.5, 234.2, 42.2, 564.2, 435.2, 444, 2424.5, 35327.7 });

          //代码精简的极端例子
Console.WriteLine(); List
<int> x = new List<int>(); x.Add(5); x.Add(10); x.Add(15); x.Add(20); x.Add(25); x.ForEach(delegate(int n) { Console.WriteLine(Math.Sqrt(n)); });

 

posted on 2012-05-01 22:57  xiacy  阅读(270)  评论(0编辑  收藏  举报