Lambda表达式的前世今生
namespace ConSole { public class Delegates { public delegate void DeleGatemodel1(); public delegate void DeleGatemodel2(int x, int y); public delegate string DeleGatemodel3(); public delegate int DeleGatemodel4(int x, int y); } /// <summary> /// Lambda表达式的前世今生 /// </summary> public class ActionShow { /// <summary> /// 最初形式 /// </summary> public static void LambdaAction1() { Delegates.DeleGatemodel2 metod1 = new Delegates.DeleGatemodel2( delegate (int x, int y) { Console.WriteLine("x的值为{0},y的值为{1}", x, y); }); metod1.Invoke(2, 3); } public static void LambdaAction2() { //箭头左边是参数,右边是方法体 Delegates.DeleGatemodel2 metod1 = new Delegates.DeleGatemodel2( (int x, int y) => { Console.WriteLine("x的值为{0},y的值为{1}", x, y); }); metod1.Invoke(2, 3); } public static void LambdaAction3() { Delegates.DeleGatemodel2 metod1 = new Delegates.DeleGatemodel2( (x, y) => //参数类型去掉,原因:传入的方法必须满足委托的约束 { Console.WriteLine("x的值为{0},y的值为{1}", x, y); }); metod1.Invoke(2, 3); } public static void LambdaAction4() { Delegates.DeleGatemodel2 metod1 = (x, y) => //去除 new Delegates.DeleGatemodel2( { Console.WriteLine("x的值为{0},y的值为{1}", x, y); }; metod1.Invoke(2, 3); } public static void LambdaAction5() { //去除大括号,条件:方法体只有一行 Delegates.DeleGatemodel2 metod1 = (x, y) => Console.WriteLine("x的值为{0},y的值为{1}", x, y); metod1.Invoke(2, 3); } //=============================================================================================== /// <summary> /// Lambda表达式使用1 /// </summary> public static void LambdaAction7() { Delegates.DeleGatemodel2 metod1 = (x, y) => Console.WriteLine("x的值为{0},y的值为{1}", x, y); metod1.Invoke(1, 2); } //结论:Lambda是一个匿名方法 //================================================================================================ //写一个带参数待返回值 public static void LambdaAction8() { Delegates.DeleGatemodel4 metod = (x, y) => { return x + y; }; //简化 Delegates.DeleGatemodel4 metod1 = (x, y) => x + y; } //写一个无参无返回值 public static void LambdaAction9() { Delegates.DeleGatemodel1 metod = () => { }; Delegates.DeleGatemodel1 metod1 = () => { Console.WriteLine("这里可以进行一些操作!"); }; } //写一个无参有返回值 public static void LambdaAction10() { Delegates.DeleGatemodel3 metod = () => ""; Delegates.DeleGatemodel3 metod1 = () => { return ""; }; } //================================================================================================ //系统自带委托 //有参无返回值 Action at = () => { };//无参无返回值 Action<string> at1 = x => { };//按f12 public delegate void Action<in T>(T obj); //这路最多只有16个参数 Action<string, int, long, Action> at2 = (x, y, z, t) => { }; //无参带返回值 f12=public delegate TResult Func<out TResult>(); Func<string> fc = () => { return ""; }; Func<string> fc1 = () => ""; public static void LambdaAction11() { Action ac = () => { }; //有参有返回值 Func<string,int, Action> fc3 = (x, a) => ac; } } }