Lambda表达式底层分析
一、我们先看下C#代码下Lamdba表达式的写法
// <summary> /// 写入日志委托 /// </summary> /// <param name="message">消息</param> delegate void WriteLog(string message); class Program { static void Main(string[] args) { { WriteLog method = (message) => { Console.WriteLine(message); }; method.Invoke("写入日志测试1"); } { WriteLog method = (message) => { Console.WriteLine(message); }; method.Invoke("写入日志测试2"); } Console.ReadKey(); } }
二、再通过反编译工具查看
internal class Program { [CompilerGenerated] [Serializable] private sealed class <>c { public static readonly Program.<>c <>9 = new Program.<>c(); public static WriteLog <>9__0_0; public static WriteLog <>9__0_1; internal void <Main>b__0_0(string message) { Console.WriteLine(message); } internal void <Main>b__0_1(string message) { Console.WriteLine(message); } } private static void Main(string[] args) { WriteLog arg_21_0; if ((arg_21_0 = Program.<>c.<>9__0_0) == null) { arg_21_0 = (Program.<>c.<>9__0_0 = new WriteLog(Program.<>c.<>9.<Main>b__0_0)); } WriteLog writeLog = arg_21_0; writeLog("写入日志测试1"); WriteLog arg_4F_0; if ((arg_4F_0 = Program.<>c.<>9__0_1) == null) { arg_4F_0 = (Program.<>c.<>9__0_1 = new WriteLog(Program.<>c.<>9.<Main>b__0_1)); } WriteLog writeLog2 = arg_4F_0; writeLog2("写入日志测试2"); Console.ReadKey(); } }
三、下面我们来看一组对比图,就非常容易的看出来了
由此我们得出的结论:编译器将lambda表达式生成一个类种类,每个lamdda也会生成一个独立的方法,然后绑定到委托的实例,所谓的lamdba表达式其实只是一个“语法糖”。