The difference between a lambda expression and an anonymous method
So why is a lambda expression shorter than an anonymous method? Does this kind of magic trick really work? Are there any important information missing? To answer these questions, let's compare the anonymous method with the lambda expression to see how the lambda expression is written.
1using System;
2
3delegate int SampleDelegate(int x, int y);
4
5class Program
6{
7 private static void Calculate(int x, int y, SampleDelegate calculator)
8 {
9 Console.WriteLine(calculator(x, y));
10 }
11
12 static void Main(string[] args)
13 {
14 // 匿名方法
15 Calculate(1, 2,
16 delegate(int x, int y) { return x + y; }); // 输出:3
17
18 // Lambda表达式
19 Calculate(1, 2, (x, y) => x + y); // 输出:3
20 }
21}
22
Comparison of List9 anonymous method and lambda expression
In this code, the following sections are written as anonymous methods and lambda expressions:
anonymous method
delegate (int x, int y) {return x + y;}
Lambda expression
(x, y) => x + y
A literal comparison will reveal the following differences:
* Delegate keyword is gone
* The return keyword is gone
* Specifies the type of the parameter int is gone
* The bracket "{}" is not
* The semicolon at the end of the line ";" Without
* NEW "=>" two characters appear
Below, for these differences, one to explain.