Lambda表达式
匿名函数
C#2.0引入,代表一个没有名字只有主体的函数,需要配合委托使用,也就是说,匿名函数其实就是一个委托对象的主体。
举个栗子:
using system;
namespace LambdaDemo
{
delegate int Operation(int x, int y);
public class Demo
{
static void Main(string[] args)
{
// 匿名函数
Operation add = delegate(int x, int y){ return x + y; };
Console.Write(Operator(add, 5, 10)); //
}
static int Operator(Operation operation, int x, int y)
{
return operation(x, y);
}
}
}
Lambda表达式
Lambda表达式是使用匿名函数的优化版本,C#3.0中引入,Lambda表达式很大程度减少了委托开发过程中的代码量。所有语言的Lambda表达式都使用Lambda运算符:" => ",读作 goes to。
语法:
() => 5;
y => y.field;
(x,y) => x + y;
(x,y) => { int temp = x + y; return temp;}
说明:
lambda表达式
左边是函数参数, "()"代表没有参数,一个参数可以不填括号,多个参数需要用括号括起来。
右边则是语句块,当只有一条语句且需要return时,语句执行结果就是返回值,可以省略return。多条语句需要用 { }包起来,且需要return的情况下不能省略。
举个栗子:
using system;
namespace LambdaDemo
{
delegate int Operation(int x, int y);
public class Demo
{
static void Main(string[] args)
{
// 匿名函数
Operation multiply = delegate(int x, int y){ return x * y; };
Console.Write(Operator(multiply, 5, 10));
Console.WriteLine();
// Lambda表达式
Console.Write(Operator((x, y) => x * y, 3, 5));
}
static int Operator(Operation operation, int x, int y)
{
return operation(x, y);
}
}
}
再举个栗子:
using System;
namespace LambdaTest
{
class Score
{
public Score(int english, int math)
{
this.english = english;
this.math = math;
}
public int english { get; set; }
public int math { get; set; }
}
class Program
{
public delegate int Total(Score score);
public delegate int Add(int math, int english);
public static int CalTotal(Score score)
{
return score.math + score.english;
}
static void Main(string[] args)
{
// 委托
Score score1 = new Score(80, 95);
Total total1 = CalTotal;
Console.WriteLine("总分:" + total1(score1));
// lambda表达式
Score score2 = new Score(97, 60);
Total total2 = score => score.english + score.math;
Console.WriteLine("总分:" + total2(score2));
// 多参数
Add add1 = (math, english) => math + english;
Console.WriteLine("总分:" + add1(80, 80));
// 多语句
Total total3 = score =>
{
var total4 = score.english + score.math;
return total4;
};
Console.WriteLine("总分:" + total3(new Score(90, 90)));
Console.ReadKey();
}
}
}