C#——Lambda表达式

346 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第25天,点击查看活动详情

lambda表达式可以理解为匿名函数的简写,他除了写法不同外,在使用上与匿名函数相同,都是配合委托或者事件来使用。

其实质上是用来代替匿名方法的,因此一个Lambda表达式也是定义了一个方法,只是形式上比匿名方法简单。只要有委托类型的地方就可以使用Lambda表达式,C#的 Lambda 表达式都使用 Lambda 运算符 =>,该运算符读为“goes to”。语法如下:

(object argOne, object argTwo) => {/*Your statement goes here*/}//函数体多于一条语句的可用大括号括起

delegate int myDel(int x,int y);    //声明委托


class Program

    {

        static void Main(string[] args)

        {

            myDel del = (x,y) =>  x+y;    //返回x+y的结果

       Console.WriteLine("values {0}",del(5,8)); //输出13  
  
        Console.ReadKey();  
     }  
  }

有关Lambda表达式的参数列表要点如下:

Lambda表达式参数列表中的参数必须在参数数量、类型和位置上与委托相匹配。

表达式参数列表中的参数不一定需要包含类型(隐式类型),除非委托有ref或out参数----此时必须注明类型(显式类型)。

如果只有一个参数,并且是隐式类型的,周围的圆括号可以被省略,否则必须有括号,如果没有参数,必须使用一组空的圆括号。

lambda内部实现过程:

编译器会创建一个匿名类,它有一个构造函数来传递外部变量。

public class AnonymousClass{

  public int lamValue;

  public AnonymousClass(int lamValue){

    this.lamValue = lamValue;

  }

  public int AnonymousMethod(int x) => x+lamValue;

}   

我们可以通过引用MSDN中的例子来演示如何通过Enumerable.Where标准查询运算符,在基于方法的查询中使用 lambda 表达式。 要注意的是,此示例中的Where方法具有一个Func委托类型的输入参数,该委托采用整数作为输入并返回一个布尔值。 Lambda 表达式可以转换为该委托。

class SimpleLambda

{

    static void Main()

    {

        // Data source.

        int[] scores = { 90, 71, 82, 93, 75, 82 };

 

        // The call to Count forces iteration of the source

        int highScoreCount = scores.Where(n => n > 80).Count();

 

        Console.WriteLine("{0} scores are greater than 80", highScoreCount);

 

        // Outputs: 4 scores are greater than 80            

    }

}

使用异步Lambda表达式

我们可以使用异步 lambda 添加事件处理程序。 若要添加此处理程序,请在 lambda 参数列表前添加一个 async 修饰符。如下例,lambda表达式被注册为一个按钮点击事件的事件处理程序。

class SimpleLambda

{

    static void Main()

    {

        // Data source.

        int[] scores = { 90, 71, 82, 93, 75, 82 };

 

        // The call to Count forces iteration of the source

        int highScoreCount = scores.Where(n => n > 80).Count();

 

        Console.WriteLine("{0} scores are greater than 80", highScoreCount);

 

        // Outputs: 4 scores are greater than 80            

    }

}