C # features-anonymous methods and lambda expressions

Source: Internet
Author: User
Document directory
  • In our programs, we often have the following requirements:
  • Read more about lambda expressions
In our programs, we often have the following requirements:

1. A temporary method is required. This method will only be used once, or is rarely used.

2. The method of this method is so short that it is shorter than the method declaration. It is really boring to write it (I call it a "one-sentence method ").

No way. It is really thankless to write such a method. For example, in some button event processing, some buttons are clicked to bring up a dialog box or call other methods. For example, the following code:

This. btnrefresh. Click + = new system. eventhandler (this. btnrefresh_click );
Private void btnrefresh_click (Object sender, eventargs E)
{
Binddata ();
}

The "refresh" button is used to call the binddata () data binding method. Therefore, we have to write a new method. Okay, C #2.0 provides us with the anonymous method:

This. btnrefresh. Click + = delegate (Object sender, eventargs e) {binddata () ;}; www.elivn.com

The boring code is gone. Do you want to know the behind-the-scenes hacker?

In fact, the compiler is still working on the next thing: it creates a new method for us, it just saves us code on the surface.

Privatevoidb _ 0 (Object sender, eventargs E)
{
This. binddata ();
}

Let's take a look at the name of the method generated by the compiler:

B _0, test is the place where the anonymous method is placed (because I put the button time in a test method). Note that, if this anonymous method is used in the instance method, the method generated by the compiler for us is also an instance method, otherwise it is a static method.

Do you think that the anonymous method is very good, which reduces a lot of code? But the use of the anonymous method is still not human-oriented. What is human-oriented? For example, you can read the program code in a natural language, which is user-friendly. In. NET 2.0, there are some new methods in the list under the system. Collections. Generic namespace. For example, find. How can we call an anonymous method:

Books. Find (delegate (Book) {return book. Price <50 ;});

The code is very simple, but it cannot be read out. Let's take a look at the lambda expression syntax:

Books. Find (Book => book. Price <50); this Lambda expression can be read as follows: give you a book and return true if its price is less than 50.

Well, let's go into the lambda expression:

After the Assembly with Lambda expressions is decompiled, we find that it is actually no different from the anonymous method. Lambda's input parameters correspond to the parameters in the delegate brackets. Since lambda expressions can infer the parameter type, the parameters here do not need to be declared.

Lambda operators are read as "goes to", followed by expressions or statement blocks (this is also different from anonymous methods. Anonymous methods can only use statement blocks but not expressions ), the following example shows the types of lambda expressions:

// The type of X is omitted. the compiler can deduce it based on the context, followed by an expression.

// The type of X is omitted. the compiler can deduce it based on the context, followed by an expression.
X => x + 1
Deleage (int x) {return x + 1 ;}
// The block is followed by the statement Block
X =>{ return x + 1 ;}
Delegate (int x) {return x + 1 ;}
// The input parameter can also contain the type. Do not forget the parentheses after the type.
(Int x) => x + 1
Delegate (int x) {return x + 1 ;}
// You can also enter multiple parameters separated by commas (,). Do not forget parentheses.
(X, y) => X + Y
Delegate (int x, int y) {return X + Y ;}
// No parameters are returned.

() => 1

Delegate () {return 1 ;}

This is the way lambda expressions are used, but there are many stories and mysteries behind lambda. Lambda expressions can be used to construct an Expression Tree, and the expression tree is as important as a tree root for the LINQ clause. We will not discuss the expression tree here. This is not something that can be clearly stated in a few words. We will discuss it further when the time is ripe.

Read more about lambda expressions

Lambda actually has a long history. The machines we use today are from the Von noriman system and belong to the Turing Machine. Before that, there was another theory called the lambda algorithm, but the Turing machine was first implemented, as a result, the lambda algorithm became a functional programming language, especially lisp. In functional programming languages, functions were the first element, function parameters, and function return values were all functions, the program has no variables and functions are nested. Functional programming languages have always existed in the ivory tower, so they are not widely used in the industry. However, in recent years, the industry prefers the "Retro" style, therefore, functional programming languages are slowly taking the stage of history. Functional programming can solve some imperative Programming Problems (or it is very troublesome to solve ). C # What should I do with function-style programming? The method defined by the original method is definitely not feasible. 2.0 of anonymous methods solve this problem in a program, but it is still not enough, lambda in 3.0 has finally been well solved. A Lambda is a delegate, and a delegate points to a method. Now we can simply pass the method as a parameter using lambda, layers can also be nested, which is very simple.

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.