background image

现在我们已经了解了大部分基础知识,但一些

 Lambda 表达式特别酷的部分还没提及。

我们来看下这段代码:

1

   

var

 a = 

5

;

2

   Func<

int

int

> multiplyWith = x => x * a;

3

 

4

   

var

 result1 = multiplyWith(

10

); 

//

 

50

5

   a = 

10

;

6

   

var

 result2 = multiplyWith(

10

); 

//

 

100

可以看到,在

 Lambda 表达式中可以使用外围的变量,也就是闭包。

1

     

static

 

void

 DoSomeStuff()

 

2

    {

 

3

       

var

 coeff = 

10

;

 

4

       Func<

int

int

> compute = x => coeff * x;

 

5

       Action modifier = () =>

 

6

      {

 

7

         coeff = 

5

;

 

8

      };

 

9

 

10

       

var

 result1 = DoMoreStuff(compute); 

//

 

50

11

 

12

      ModifyStuff(modifier);

13

 

14

       

var

 result2 = DoMoreStuff(compute); 

//

 

25

15

    }

16

 

17

     

static

 

int

 DoMoreStuff(Func<

int

int

> computer)

18

    {

19

       

return

 computer(

5

);

20

    }

21

 

22

     

static

 

void

 ModifyStuff(Action modifier)

23

    {