Delegation, anonymous functions, and lambda expressions

Source: Internet
Author: User

I have been familiar with delegation a long time ago, but I have never used much of it for him. I am a newbie and I don't have much advanced code to write, however, when I recently looked at the msdn Microsoft class library, I found that many of Microsoft's class libraries were commissioned. So I decided to study it well and deepen my impression on him, by the way, write your own insights and ideas so that you can have a deeper understanding. Due to your limited level, you are welcome to discuss more and solve problems and make progress together.

On msdn, the definition of delegation is: Delegate indicates the type of reference to methods with specific parameter lists and return types. In my opinion, the main features of delegation are:

1. Pass a method as a parameter to another function. In this way, the method can be expanded. For example, when we compare two data of the same type (two objects of the same class, we only need to pass the comparison objects and comparison rules to the comparison method. This rule can be passed in as a delegate. We do not know how to compare different types of objects, during the comparison, we only need to pass in the object and the corresponding comparison rules. See the following code:

Namespace delegatetest {internal class program {Private Static void main (string [] ARGs) {person p1 = new person {name = "p1", age = 19 }; person P2 = new person {name = "p2", age = 22}; // enter the comparison object and the specific comparison rule compareperson (P1, P2, comparepersonrule );} // define the delegate Public Delegate bool comparerule (int x, int y); // This method is the specific comparison method pointed to by the delegate public static bool comparepersonrule (int x, int y) {return x> Y;} // compare P For eson data, you do not need to know the specific comparison rules. You only need to input a delegate. The specific comparison is implemented by the specific method pointed by the delegate comparerule to achieve public static void compareperson (person P1, person P2, comparerule) {If (comparerule (p1.age, p2.age) {console. writeline (p1.name + "older than" + p2.name +! "); Console. readkey ();} else {console. writeline (p1.name +" younger than "+ p2.name +! "); Console. readkey () ;}} public class person {public int age {Get; set;} public string name {Get; Set ;}}}}

When comparing object types, you only need to change to different delegate entities, which can greatly extend the code availability.

2. The delegate is used for the callback function. The callback function is to pass a method to another method for execution. C # has many callback functions, such as asynchronous operations. Here is an example:

Namespace delegatecallbacktest {// <summary> /// delegate /// </Summary> /// <Param name = "S1"> </param> /// <Param name = "S2"> </param> // <returns> </returns> Public Delegate string processdelegate (string S1, string S2); Class program {static void main (string [] ARGs) {/* Call Method */test T = new test (); string R1 = T. process ("text1", "text2", new processdelegate (T. process1); console. writeline (R1); console. readkey () ;}} public class test {Public String process (string S1, string S2, processdelegate process) {return process (S1, S2);} Public String process1 (string S1, string S2) {return S2 + S1 ;}}}

The delegate method is finally executed in the process method of test, which is the simplest callback. There are many examples of delegate callback in C #, so I won't talk about it here.

3. For multicast delegation, the event is implemented through multicast delegation, with one plus minus.

When it comes to delegation, I naturally cannot leave anonymous functions. I feel that anonymous functions are generated to facilitate delegation writing. Maybe my understanding of them is not yet in place, the anonymous method is a new feature introduced by C #2.0. It allows developers to declare their own function code inline (Inline) without using the delegate function (delegate function. An anonymous method usually requires a temporary method, which is rarely used. 2. The code of this method is very short and may even be used if it is shorter than the method declaration. You can think of the C # anonymous method as a convenient way to implement and delegate the function. If you take a look at the Il results obtained by the implementation of anonymous and naming methods, you will find that the differences between the two are very small. When the compiler encounters an anonymous method, it creates a naming method in the class and associates it with the delegate. Therefore, the performance of anonymous methods is very similar to that of naming methods during running. The increase in performance is reflected in the production efficiency of developers rather than the execution during running. In C #1.0, you create a delegated instance by explicitly initializing the delegate using a method defined elsewhere in the code. C #2.0 introduces the concept of anonymous methods, as a way to compile unnamed inline statement blocks that can be executed in a delegate call. C #3.0 introduces lambda expressions, which are similar to anonymous methods but more expressive and concise. These two functions are collectively referred to as "anonymous functions ". Lambda expressions are usually used for. NET Framework 3.5 and later applications.

The following example demonstrates the development of the delegate creation process from C #1.0 to C #3.0:

 
 
class Test{    delegate void TestDelegate(string s);    static void M(string s)    {        Console.WriteLine(s);    }    static void Main(string[] args)    {        // Original delegate syntax required         // initialization with a named method.        TestDelegate testDelA = new TestDelegate(M);        // C# 2.0: A delegate can be initialized with        // inline code, called an "anonymous method." This        // method takes a string as an input parameter.        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };        // C# 3.0. A delegate can be initialized with        // a lambda expression. The lambda also takes a string        // as an input parameter (x). The type of x is inferred by the compiler.        TestDelegate testDelC = (x) => { Console.WriteLine(x); };        // Invoke the delegates.        testDelA("Hello. My name is M and I write lines.");        testDelB("That‘s nothing. I‘m anonymous and ");        testDelC("I‘m a famous author.");        // Keep console window open in debug mode.        Console.WriteLine("Press any key to exit.");        Console.ReadKey();    }}/* Output:    Hello. My name is M and I write lines.    That‘s nothing. I‘m anonymous and    I‘m a famous author.    Press any key to exit. */
The following is a summary on msdn:

Lambda expressions are anonymous functions that can be used to create a delegate or expression directory tree. By using lambda expressions, you can write local functions that can be passed as parameters or returned as function call values. Lambda expressions are particularly useful for writing a LINQ query expression. To create a Lambda expression, specify the input parameter on the left side of the lambda operator => (if any), and then enter the expression or statement block on the other side. For example, Lambda expression x => X * x specifies the parameter named X and returns the square value of X.

=> The operator has the same priority as the value assignment operator (=) and is a union operation on the right (see "associativity" in the "operators" document ).

Lambda is used as a parameter for standard query operators (such as where) in method-based LINQ queries.

When you use method-based syntax to call the where Method in the enumerable class (for example, in the same way as in LINQ to objects and LINQ to XML), the parameter is the delegate type system. func <t, tresult>. Using lambda expressions to create a delegate is the most convenient. For example. LINQ. when the same method is called in the queryable class (for example, in LINQ to SQL), the parameter type is system. LINQ. expressions. expression <func>, in which func is any func delegate with a maximum of 16 input parameters. Similarly, lambda expressions are just a simple way to construct the directory tree of the expression. Although the objects created through Lambda have different types, Lambda makesWhereThe call looks similar.

In the previous example, note that the delegate signature has an implicit type input parameter of the int type and returns the int type. A Lambda expression can be converted to a delegate of this type because it also has an input parameter (X) and a compiler can implicitly convert the return value to an int type. (Type inference will be discussed in detail in the following sections .) When you call a delegate using input parameter 5, it returns Result 25.

Lambda is not allowed on the left side of the IS or as operator.

All limitations applicable to anonymous methods also apply to lambda expressions.

Lambda is a more convenient anonymous function. It can be said that it is generated for delegation. The above is just for your own ignorance, and I hope to have more exchanges with you.

 

 

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.