The first part of the Lambda Master Road

Source: Internet
Author: User

Transfer http://www.cnblogs.com/lazycoding/archive/2013/01/06/2847574.html Introduction

Lambda expressions are a powerful tool for making your code more dynamic, easy to scale, and faster (you'll know why this article has been read). can also be used to reduce potential errors. You can also take advantage of static input and smart hints, just like in vs.

Lambda expressions are presented in the. NET Framework 3.5. and has played a significant role in some of the technologies within LINQ and ASP. If you consider the implementation of the various controls in ASP. You'll find out. The secret is that most of them use lambda expressions. Along with lambda expressions, using HTML extension methods will make it possible to create models in the background.

This article will cover the following knowledge.

1. A short description of what the-LAMBDA expression is and why it differs from the anonymous method (which we used previously)
2. Approaching the performance of a lambda expression-in which case the lambda will improve/lose performance compared to the standard method
3. What is the in-depth-LAMBDA expression in the MSIL code
4. Some schemas from the JS world are mapped to C #
5. Things that can improve performance, and that the code looks pretty comfortable using lambda.
6. Some of the new models I have proposed-of course, others have come forward. But this is the result of my thinking.

If you expect this article to be an introductory tutorial I might want to disappoint you, unless you are really good and smart, of course I am not such a person, so I would like to make a statement in advance: In order to read this article you may need some advanced knowledge of C #, and the C # more understanding.

You should expect this article to try to explain something to you and explain some interesting questions, at least for me. Finally, I'll show you some real-world examples and patterns, and as I said, lambda expressions simplify a lot of things. It is therefore useful to write explicit patterns.

Background knowledge-What is a lambda expression

In c#1.0, the delegate is proposed, which makes the transfer function possible, in a word, the delegate is a strongly typed function pointer, but the delegate is more powerful than the pointer. Generally passing a function requires the following steps.
1. Write a delegate (like a class) that contains the return type and parameter type
2. Use a delegate as the parameter type of a function, so that the function can accept and delegate the same signature function as described
3. Pass a function of a delegate type to the delegate, creating a delegate instance.

If it sounds complicated, it's really complicated, but it's necessary. (Although not a rocket, but more code than you think), step three is not required and the compiler will do it for you, but steps 1 and 2 are essential.

Fortunately c#2.0 appeared generics, and now we can also write generic classes, methods, and more importantly, generic delegates, however, until the. NET Framework 3.5. Microsoft realizes that there are actually only two generic delegates (with some different overloads, of course) that cover 99% of the usage:

1.Action does not have any input parameters or output parameters.
2.ACTION<T1,... t16> requires 1-16 parameters, no output parameters.
3.func<t1....t16,tout> requires 0-16 parameters, one output parameter

The action and its corresponding generic version (just an action, something to do) return void. Func can return the last parameter to the specified type, through both of these delegate types, which we actually, in most cases. The first part of the three steps mentioned above is not written. And the second step is still needed.

So what do we do if we want to run the code? The problem can be solved in c#2.0. In this version. We can create a delegate method, which is an anonymous method, and the syntax has not been popular, and a fairly simplified version of the anonymous method looks like this:

func<double>  delegate (double x) {return x * x;}     

To improve this syntax, welcome to the realm of lambda expressions. First of all, how did this lambda name come from? In fact. From the mathematical λ calculus, it is more accurate that he is a formal system in mathematics. Used for expression evaluation through variable binding and substitution, so we have 0-n input parameters and a return value, and in programming, there can be no return value

Let's take a look at some examples of lambda expressions
//The compiler can identify and then can pass Dummylambda ();var Dummylambda = () = {Console.WriteLine ("Hallo World from a Lambda expression!"); };//Can be used func< by a double y = square (25);Doubledouble> Square = x = x *X//You can use func< by analogous to double z = Product (9, 5);DoubleDoubleDouble> Product = (x, y) = x *Y//Can be used with action< like Printproduct (9, 5);DoubleDouble> printproduct = (x, y) + = {Console.WriteLine (x *y); };//can be passed like var sum = dotProduct (new double[] {1, 2, 3}, new double[] {4, 5, 6}); func<Double[],Double[],Double> dotProduct = (x, y) = ={var Dim =Math.min (X.length, y.length);var sum =0.0;Forvar i =0; I! = Dim; i++) sum + = X[i] + Y[i]; sum;}; // can be passed like var result = Matrixvectorproductasync (...); Use Func<double[, "double[], double[]=async (x, y) => {var sum = 0.0; /* do some stuff ... */return sum;};    

We can learn something from the code snippet above.

    • If we have only one input parameter, we can omit ()
    • If we have an input parameter and return one, we can omit the {} and return keyword
    • We can get our lambda expression to execute asynchronously, just add the Async keyword.
    • The VAR keyword is generally not available, only in rare cases.

Of course we can use Var as usual, which is optional if we specify the parameter type. Because a type can be inferred from the type of the delegate. And the following is wrong. Take a look at the following example

var square = (double x) = x * x;  var stringlengthsquare = (string s) = = S.length * s.length;  var squareandoutput = (string s) = = {var sqz = x * x; Console.WriteLine ("information by {0}: The square of {1} is {2}.") , S, X, SQZ);};             

We all know most of the basics. But some pretty cool stuff (which makes them useful in many cases), let's consider the following code snippet

5;  var multiplywith = x = x * A;  var result1 = Multiplywith (//);  var result2 = Multiplywith (//         

This is possible. So you can use the other variables. It's more special than you think. Because the capture variable appears here. This causes a closure to occur, considering the following scenario.

voidDoSomeStuff () {var Coeff =10var compute = (int x) = Coeff * X; var modifier = () => {Coeff = 5;}; var result1 = Domorestuff (compute); Modifystuff (modifier); var result2 = Domorestuff (compute);} int Domorestuff (Action computer) {return computer (5void Modifystuff (Action modifier) {modifier ();}    

Guess what happens to this piece of code. First we create a local variable. and two lambda expressions, the first lambda expression shows that it is possible to access local variables in other local areas. It's unbelievable. This means that we want to protect a variable, but in fact he can still be accessed in other ways. Regardless of whether the method is defined internally or in other classes.

The second lambda expression simulates a lambda expression to modify the external domain variable. This means that we can modify our local variables in other ways, simply by passing a lambda expression created in the corresponding domain. So, I think closures are a bit of a magical color. Just like parallel programming. may result in unexpected results. Just like in parallel programming in the competition situation.

The first part of the Lambda Master Road

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.