background image

 

4

  {

 

5

     Console.WriteLine(

"Hello World from a Lambda expression!"

);

 

6

  };

 

7

 

 

8

   

//

 

Can be used as with double y = square(25);

 

9

   Func<

double

double

> square = x => x * x;

10

 

11

   

//

 

Can be used as with double z = product(9, 5);

12

   Func<

double

double

double

> product = (x, y) => x * y;

13

 

14

   

//

 

Can be used as with printProduct(9, 5);

15

   Action<

double

double

> printProduct = (x, y) => { Console.WriteLine(x * y); };

16

 

17

   

//

 

Can be used as with 

18

   

//

 

var sum = dotProduct(new double[] { 1, 2, 3 }, new double[] { 4, 5, 6 });

19

   Func<

double

[], 

double

[], 

double

> dotProduct = (x, y) =>

20

  {

21

     

var

 dim = Math.Min(x.Length, y.Length);

22

     

var

 sum = 

0.0

;

23

     

for

 (

var

 i = 

0

; i != dim; i++)

24

       sum += x[i] + y[i];

25

     

return

 sum;

26

  };

27

 

28

   

//

 

Can be used as with var result = matrixVectorProductAsync(...);

29

   Func<

double

[,], 

double

[], Task<

double

[]>> matrixVectorProductAsync =

30

     

async

 (x, y) =>

31

    {

32

       

var

 sum = 

0.0

;

33

       

/*

 

do some stuff using await ... */

34

       

return

 sum;

35

     };

从这些语句中我们可以直接地了解到:

如果仅有一个入参,则可省略圆括号。

如果仅有一行语句,并且在该语句中返回,则可省略大括号,并且也可以省略

 return 

关键字。

通过使用

 async 关键字,可以将 Lambda 表达式声明为异步执行。

大多数情况下,

var 声明可能无法使用,仅在一些特殊的情况下可以使用。

在使用

 var 时,如果编译器通过参数类型和返回值类型推断无法得出委托类型,将会抛出

 

“Cannot assign lambda expression to an implicitly-typed local variable.” 的错误提示。来看下如
下这些示例: