1
class Test
2

{
3
delegate double Calc(double x);
4
5
static void Main(string[] args)
6
{
7
double[] a =
{ 0.0, 0.5, 1.0 };
8
double[] results = Apply(a, new Calc(Square));
9
foreach (double d in results)
10
{
11
Console.WriteLine(d);
12
}
13
14
Console.ReadLine();
15
}
16
17
public static double Square(double x)
18
{
19
return x * x;
20
}
21
22
static double[] Apply(double[] a, Calc f)
23
{
24
double[] result = new double[a.Length];
25
for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
26
return result;
27
}
28
}
整个代码虽然比较繁琐,但确很明了。
2



3

4

5

6



7



8

9

10



11

12

13

14

15

16

17

18



19

20

21

22

23



24

25

26

27

28

自从2.0推出了匿名方法之后,上面的写法就不够紧跟时代潮流了,应该这么写了:
1
class Test
2

{
3
delegate double Calc(double x);
4
5
static void Main(string[] args)
6
{
7
double[] a =
{ 0.0, 0.5, 1.0 };
8
double[] results = Apply(a, delegate(double x)
{ return x * x; });
9
foreach (double d in results)
10
{
11
Console.WriteLine(d);
12
}
13
14
Console.ReadLine();
15
}
16
17
static double[] Apply(double[] a, Calc f)
18
{
19
double[] result = new double[a.Length];
20
for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
21
return result;
22
}
23
}
代码是变少了,但是说实话,有的时候看这样的代码怎么好像就突然看不明白了呢?
2



3

4

5

6



7



8



9

10



11

12

13

14

15

16

17

18



19

20

21

22

23

即使这样,微软还是不放过像我这样脑袋不太好使的同志,它竟然推出了Lambda表达式,也就是说,上面的代码也不够先进了,应该这样了:
1
class Test
2

{
3
delegate double Calc(double x);
4
5
static void Main(string[] args)
6
{
7
double[] a =
{ 0.0, 0.5, 1.0 };
8
double[] results = Apply(a, x => x * x);
9
foreach (double d in results)
10
{
11
Console.WriteLine(d);
12
}
13
14
Console.ReadLine();
15
}
16
17
static double[] Apply(double[] a, Calc f)
18
{
19
double[] result = new double[a.Length];
20
for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
21
return result;
22
}
23
}
那一行代码彻底让我抓狂了,代码可以简洁到这种地步,语法竟然变化这么快,微软简直太牛了!
2



3

4

5

6



7



8

9

10



11

12

13

14

15

16

17

18



19

20

21

22

23

但是,你如果看一下这三段代码的IL时,你就会发现它们几乎是一模一样的,不一样的仅仅是后面两段代码在编译的时候,编译器自动为我们生成了一个方法。
这里仅仅是初步介绍了一下怎样把一个委托从最初的形式转化为Lambda表达式的形式,相信对新手理解起来会有一定的帮助,深入地介绍限于本人水平有限,也不能多做介绍了,还是看看MSDN吧。