From: Blog Garden - Halfway Alone
Original address: http://www.cnblogs.com/banluduxing/p/9007494.html
This article is reproduced from http://www.cnblogs.com/banluduxing , please indicate the source.
Before reading, make sure you have a basic understanding of delegates .
The first step of the prototype of lambda expression
In the delegate article, the bound methods are all named functions. In order to simplify writing, they can be replaced by anonymous functions.
public delegate void Write(); public delegate void Read(int x, string str); public delegate int Get(int y); static void Main(string[] args) { Write write = new Write(delegate() { Console.WriteLine("write"); }); Read read = new Read(delegate (int x, string y){ Console.WriteLine("read"); }); Get get = new Get(delegate (int x) { return 1; }); }
The second step of the prototype of lambda expression
Replace delegate() with ()=>, because the method and the delegate parameter signature are consistent, the parameter type can also be removed, the above can be simplified as
Write write = new Write(()=> { Console.WriteLine("write"); }); Read read = new Read(( x,y)=>{ Console.WriteLine("read"); }); Get get = new Get((x) =>{ return 1; });
The third step of the prototype of lambda expression
Delegate initialization can directly bind the method, no need for new, the method body has only one line of code, and {} can be omitted, and if there is return, the return keyword can also be removed, which is simplified to
Write write = () => Console.WriteLine("write"); Read read = (x, y) => Console.WriteLine("read"); Get get = (x) => 1;
Just remember that the essence of a lambda expression is a method, then the lambda expression becomes less complicated