代码改变世界

委托学习(3)

2014-08-08 16:52  wuzhang  阅读(324)  评论(0编辑  收藏  举报

1.1 匿名方法

  在上次我们提到,创建委托实例时都必须明确指定使用的方法。C# 2.0引入了匿名方法,及允许与委托相关联的的代码块以内联方式写入使用委托的位置,从而方便地将代码块直接"绑定"到委托实例。使用匿名方法就可以降代码块直接作为委托的参数,而不需要先定义方法,再将方法作为参数来创建委托。匿名方法还能够对包含它的函数成员的拒不状态进行共享访问,如果要使用具名方法来实现同样的状态共享,就需要将局部变量提升为一个辅助类的字段。

  匿名方法由delegate,可选的参数表和包含{}内的代码块组成。

  delegate(【参数表】)

  {

    【代码块】

  };

  【参数表】:可选

  委托的参数表和返回值都必须与匿名方法相兼容,才能进行从匿名方法到委托类型的隐式转换。

下面看一个例子:

 

 1 using System;
 2 
 3 
 4 delegate double Funcation(double x);
 5 
 6 namespace Delegate3
 7 {
 8     class Test
 9     {
10         public static double[] Apply(double[] a, Funcation f)
11         {
12             double[] result = new double[a.Length];
13             for (int i = 0; i < a.Length; i++)
14             {
15                 Console.WriteLine("参数:"+a[i]);
16                 result[i] = f(a[i]);
17                 Console.WriteLine("结果:" + result[i]);
18 
19             }
20             return result;
21         }
22 
23         public static double[] MultiplyAllBy(double[] a, double factor)
24         {
25             return Apply(
26                             a,
27                             delegate(double x)    //声明匿名方法
28                             {
29                                   return x * factor;
30                             }
31                 );
32         }
33     }
34     class Program
35     {
36         static void Main(string[] args)
37         {
38             double[] a = { 0.0, 0.5, 1.0 };
39             double[] squares = Test.Apply(
40                                         a, delegate(double x)  //匿名方法
41                                         {
42                                             return x * x;
43                                         }
44                 );
45             double[] doubles = Test.MultiplyAllBy(a, 2.0);
46             Console.ReadKey();
47         }
48     }
49 }

运行结果: