lambda表达式(lambda expression)实际上是匿名函数一种表示形式,即没有函数名的函数:参数列表=>表达式或语句块,在我看来主要目是为了简化代码编写,
提高代码可读性而提供的语法糖。
C#中lambda表达式使用“=>”运算符表示,可读作“goes to”,多参数多语句时用“(x,y)=>{语句块};”参数和语句块分别需要用小括号和大括号括起,
单参数单语句则可以“x=>语句;”无括号;无参数则表示为()=>表达式.
简单举例说明lambda表达式的使用:
delegate void delegateLambda(); delegate void delegateLambda2(int x); delegate void delegateLambda3(int x,int y); private void btnCalculate_Click(object sender, EventArgs e) { delegateLambda lam = () => MessageBox.Show("无参数lambda表达式"); lam(); delegateLambda2 lam2 = x => { MessageBox.Show("单一参数lambda表达式x=:"+x.ToString()); }; lam2(50); delegateLambda3 lam3 = (x, y) => { string result = (x + y).ToString(); MessageBox.Show(result); }; lam3(10, 20); }
也可通过lambda表达式实现委托:
public partial class MainDisplay : Form { public MainDisplay() { InitializeComponent(); } List<Student> studentList = new List<Student>(); private void MainDisplay_Load(object sender, EventArgs e) { Student s1 = new Student() { Name = "张三", Id = "1", age = 13, ClassId = "5", Sex = "男" }; Student s2 = new Student() { Name = "李四", Id = "2", age = 14, ClassId = "5", Sex = "男" }; Student s3 = new Student() { Name = "王五", Id = "3", age = 17, ClassId = "2", Sex = "男" }; Student s4 = new Student() { Name = "赵六", Id = "4", age = 16, ClassId = "2", Sex = "女" }; studentList.Add(s1); studentList.Add(s2); studentList.Add(s3); studentList.Add(s4); } private void btnSearch_Click(object sender, EventArgs e) { List<Student> student=new List<Student>(); //查询年龄大于30的学生 student = studentList.Where(Stu => Stu.age > 15).ToList(); foreach (Student stu in student) { MessageBox.Show(stu.Name); } } } public class Student { public string Id { get; set; } public string Name { get; set; } public string Sex { get; set; } public int age { get; set; } public string ClassId { get; set; } }
无论传统匿名方法还是Lambda 表达式实现的委托,原理都是在编译过程中,创建了一个静态的方法实例委托的对象。也就是说匿名方法和Lambda 表达式在CIL中都是采用命名方法实例化委托。