Reprint C # anonymous function delegates and lambda expressions

Source: Internet
Author: User

Reprint Original Source: http://blog.csdn.net/honantic/article/details/46331875

Anonymous Functions

Anonymous functions (Anonymous function) are expressions that represent the "inline" method definition. The anonymous function itself and its interior have no value or type, but can be converted to a compatible delegate or expression tree type (Learn more). The calculation of an anonymous function transformation depends on the target type of the transformation: if it is a delegate type, the conversion is evaluated to a delegate that references the method defined by the anonymous function, and if it is an expression tree type, the transformation evaluates the expression tree that represents the method structure as an object structure.
Anonymous functions have two syntactic styles:lambda expressions (lambda-expression) and anonymous method expressions (anonymous-method-expression). In almost all cases, lambda expressions are more expressive than an anonymous method expression. However, the latter is still retained in the C # language for backwards compatibility.
Lambda expression:
Async Optional (anonymous function signature) = = (anonymous function body)
An anonymous method expression:
Async Optional Delegate (explicit anonymous function signature) optional {code block}

the anonymous function signature can include two kinds, one is implicit anonymous function signature and the other is explicit anonymous function signature :
Implicit function Signature: (P), (P1,P1)
Explicit function Signature: (int p), (int p1,int p2), (ref int p1,out int p2)
An anonymous function body can be an expression or a block of code.

As we can see from the above, the parameter form of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each parameter is explicitly declared, and in the implicitly typed argument list, the type of the parameter is inferred from the context in which the anonymous function appears.
When a lambda expression has only one implicitly typed parameter, the argument list can omit parentheses, which means:
(parameter) = = Expression
can be shortened to
parameter = = Expression

examples of some anonymous functions
x = x + 1//implicitly typed, function body is an expression
x = {return x + 1;}//implicitly typed, function body as code block
(int x) + x + 1//explicit typing, function body is an expression
(int x) + = {return x + 1;}//explicit typing, function body as code block
(x, y) = x * Y//multi-parameter
() = Console.WriteLine ()//No parameters
Async (T1, t2) = await T1 + await T2//Async
delegate (int x) {return x + 1;}//anonymous function method expression
Delegate {return 1 + 1;}//Parameter list omitted

the difference between a lambda expression and an anonymous method expression:
When there are no parameters, the anonymous method expression allows the argument list to be completely omitted, which can be converted to a delegate type with an arbitrary value argument list, and the lambda expression cannot omit the parentheses () of the argument list.
Lambda expressions allow you to omit and infer type parameters, and an anonymous method expression requires that you explicitly declare the parameter type.
The body of a lambda expression can be an expression or a block of code, and the body of an anonymous method expression must be a code block.
Only lambda expressions can be compatible with the expression tree type.

Delegate

A delegate is a reference to a method, or an instance of a delegate is an object that points to a method, which is a simple but very powerful concept.
Delegates in C # are used to handle situations in other languages (such as C + +, Pascal, etc.) that need to be handled with a function pointer. However, unlike C + +, delegates are completely object-oriented; C + + pointers only point to member functions, while delegates encapsulate both instances and methods of objects, and delegates are fully type-safe, and only when the signature of a function matches the signature of the delegate can the delegate point to the method, cannot be called when the delegate does not have a valid pointing method.

  some points of knowledge about delegates:

  1. Delegates are type-safe
The return type of a delegate type must be void or output safe, and all parameter types of a delegate type must be input-safe.

  2. The delegate type is name-equivalent, not struct-equivalent
That is, for two delegate types, even if they have the same argument list and return type, they will still be treated as two different delegate types.
For example:
delegate int A (int x);
delegate int B (int x);
A and B are two different delegates.

However, there are two structure-like delegates whose instances can point to the same method.

  3. Invocation list of Delegates (Multicast delegates)
The collection of methods encapsulated by the delegate instance is called the invocation list.
When we create a delegate instance from a method, the instance encapsulates this method, and the invocation list in that instance contains an "entry point." When we combine multiple non-empty delegate instances, their invocation lists are concatenated together to form a new invocation list with multiple "entry points" in the new invocation list.
The combination of delegates is done using the two-tuple operator + and + =, which can also be removed using-and-=.

The following example shows the instantiation of multiple delegates and their corresponding invocation lists:

1 Delegate voidDintx)2 class3 {4      Public Static voidM1 (inti) {...}5      Public Static voidM2 (inti) {...}6 }7 classTest8 {9     Static voidMain ()Ten     { OneD CD1 =NewD (C.M1);//M1 AD CD2 =NewD (C.M2);//M2 -D CD3 = CD1 + CD2;//M1 + M2 -D CD4 = CD3 + CD1;//M1 + M2 + M1 theD CD5 = CD4 + CD3;//M1 + M2 + M1 + M2 -     } -}

When instantiating CD1 and CD2, they encapsulate a single party separately. When instantiating CD3, the list it invokes has two methods M1 and M2, and the order is the same. The CD4 invocation list contains M1, M2, and M1 in sequence. Finally, the CD5 invocation list contains M2, M1, M1, and M2 in turn.

4. Invocation of a delegate

When a delegate instance is invoked, each method in the list is called in the order of the invocation list, and any method that follows the call list will not be called when an exception occurs during the call.

1 usingSystem;2 Delegate voidDintx);3 classC4 {5      Public Static voidM1 (inti)6     {7Console.WriteLine ("C.M1:"+i);8     }9 Ten      Public Static voidM2 (inti) One     { AConsole.WriteLine ("C.M1:"+i); - } -  the      Public  voidM3 (inti) -     { -Console.WriteLine ("c.m2:"+i); -     } + } -  + classTest A { at     Static voidMain () -     { -D CD1 =NewD (C.M1);//M1 -CD1 (-1);//Call CD1 -  -D CD2 =NewD (C.M2);//M2 inCD2 (-2);//Call M2 -  toD CD3 = CD1 + CD2;//M1 + M2 +CD3 (Ten);//call M1, M2 -  theCD3 + =CD1; *CD3 ( -);//call M1, M2, M1 in turn $ Panax Notoginsengc C =NewC (); -D CD4 =NewD (C.M3);  theCD3 + =CD4; +CD3 ( -);//call M1, M2, M1, M3 A  theCD3-= CD1//remove the last M1 +CD3 ( +);//call M1, M2, M3 in turn -  $CD3-=CD4;  $CD3 ( -);//call M1, M2 -  -CD3-=CD2 theCD3 ( -);//Call M1 - WuyiCD3-= CD2//This is the CD3 call list does not have CD2, the removal does not take effect, no error theCD3 ( -);//Call M1 -  WuCD3-=CD1 -         //CD3 (70); //if called, System.NullReferenceException exception will be reported About     } $}
lambda expression

Since c#3.0, you can use a new syntax to assign the implementation code to a delegate: a lambda expression. A lambda expression can be used wherever there is a delegate parameter type. Where anonymous methods are used, you can use lambda expressions instead, for example:

1func<string,string> = Delagate (stringpara)2 {3Para + ="Hello world!";4     returnparam;5 }6 can be written7func<string,string> = para=>8 {9Para + ="Hello world!";Ten     returnpara; One}

The lambda expression operator, "= =", lists the required parameters on the left, and the code implementation of the method to which the lambda variable is assigned is defined on the right.
We note that whenever we need to introduce an anonymous method, we need to precede the delegate keyword, and the parameter list needs to be typed. Lambda expressions provide a more concise and natural syntax, and are widely involved in more advanced aspects of C #. In short, we should use lambda expressions instead of anonymous methods.
For example:

1  Public class Person2 {3     stringName;4     intAge ;5 }6 7List<person> personlist =NewList<person>();8 9Personlist.find (Delegate(Person P) {Retrun p.age== A;});Ten //can be written OnePersonlist.find (p=>p.age== A);

Reprint C # anonymous function delegates and lambda expressions

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.