A lambda expression is an anonymous function. Evolution steps: General Method delegate = = Anonymous function delegate = = lambda expression
Lambda expression is not unfamiliar, his previous existence is anonymous function, so to talk about lambda expression, we have to talk about anonymous functions, to talk about anonymous functions, then have to talk about the delegation.
The delegate is very well understood, similar to a function pointer in C + + (pointing to a method), and the delegate constrains the signature of the method to be directed (consisting of the return type and parameters). First, define a delegate such as:
Delegate int Processint (int i);
Defines that a delegate can pass a method like a variable. Such as:
void Sample (Processint Pro)
At this point we need to write the same method as the delegate signature:
int Double (int i) { return2; } int Divide (int i) { return2); }
For a very simple operation, such a repetitive definition method is cumbersome, not elegant, and. NET 2.0 has an anonymous method, like this:
Sample (delegate(intreturn2;}); //
Now, to adjust the method, I do not have to define the method, but write the program is still to hit a lot of characters, good, lambda expression came. It is written in this way:
2); // lambda expression
Or, that way.
Sample2 ((i, k) = i *
Code:
Execute test to verify the results.
Delegate intProcessint (inti); Delegate intADD (intIintk); intDouble (inti) {returnI2; } intDivide (inti) {returnConvert.ToInt32 (I/2); } voidSample (Processint Pro) {inti = -; Console.WriteLine (Pro (i)); } voidSample2 (Add Pro) {inti = -; intK =5; Console.WriteLine (Pro (i,k)); } Public voidTest () {Sample (Double); Sample (Divide); //DelegateSample (Delegate(inti) {returnI2; });//Anonymous MethodsSample (i = i *2);//lambda expressionSample (i = Convert.ToInt32 (I/2)); Sample2 ((i, K)= i *k); }
View Code
Lambda expression Evolution