C#中Lambda表达式的三种写法

一、历史版本

delegate void StudentDelegate(string name, int age); public class LambdaTest{public void Show(){DateTime dateTime = DateTime.Now; //历史//版本1{StudentDelegate student = new StudentDelegate(PrintStudent); student("葛优", 1); }}}public void PrintStudent(string name,int age){Console.WriteLine($"我的名字是:{name},我的年龄是{age}"); }

二、版本二:访问局部变量
delegate void StudentDelegate(string name, int age); public class LambdaTest{public void Show(){DateTime dateTime = DateTime.Now; //版本2(这样写的话可以访问局部变量){StudentDelegate student = new StudentDelegate( delegate (string name, int age){Console.Write(dateTime); Console.WriteLine($"我的名字是:{name},我的年龄是{age}"); }); student("王朝伟", 1); }}}

三、版本三: “=>”
delegate void StudentDelegate(string name, int age); public class LambdaTest{public void Show(){DateTime dateTime = DateTime.Now; //版本3(=>念成gose to){StudentDelegate student = new StudentDelegate((string name, int age)=>{Console.Write(dateTime); Console.WriteLine($"我的名字是:{name},我的年龄是{age}"); }); student("刘德华", 1); }{Action action = () => Console.WriteLine("无返回值,无参数"); Action action1 = d => { Console.WriteLine( $"带一个参数:{d}"); }; action1(dateTime); Action action2 = (d, i) => { Console.WriteLine($"带两个参数:{ d} ,{ i}"); }; action2(dateTime, 3); Func func=()=>{ return DateTime.Now; }; //带返回值DateTime dateTime1 = func(); //调用Lambda获取值 Console.WriteLine(dateTime1); Func func2 = () => DateTime.Now; //带返回值Console.WriteLine(func2()); }}}

【C#中Lambda表达式的三种写法】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读