Entrusted and anonymous entrusted

Source: Internet
Author: User

Entrusted and anonymous entrusted

Originally, I wanted to write an article "past and present of the Delegate and lambda expressions", but only the delegate has already written a lot of content, so I will separate the content about the Lambda expression and write it later.

I don't know who invented the Lambda expression. I only remember that when I first came into contact with the Lambda expression in VS2008, I thought it was invented by Microsoft.

Lambda expressions have become more and more popular since I started to use them. In Java 8, kotlin is more popular for C #, F # has been extensively copied (C # has never been so familiar with Java ). In fact, this fully demonstrates the importance of Lambda expressions. To clarify Lambda, we must first clarify the delegation.

Delegate:

Suppose now we want to develop a program for processing two integers (assuming processing the addition operation first)

Public class Worker {// <summary> /// process two data sets /// </summary> /// <param name = "a"> </param> // /<param name = "B"> </param> // <returns> </returns> public int HandleTwoNumber (int, int B) {return a + B ;}} static void Main (string [] args) {int a = int. parse (Console. readLine (); int B = int. parse (Console. readLine (); Worker worker = new Worker (); int result = worker. handleTwoNumber (a, B); Console. writeLine (String. format ("Result: {0}", result); string p = Console. readLine ();}

If we need to change it to a subtraction operation after a period of time:

public class Worker        {            public int HandleTwoNumber(int a,int b)            {                return a - b;            }        }

Although a + B is slightly changed to a-B, there may be several changes in the future (from subtraction to division .........). Changes should be encapsulated. Here we can abstract the operational behaviors of a and B. What abstraction should we use?Delegate

public class Worker        {            public delegate int TwoNumberHandleMethodDelegate(int x, int y);            public int HandleTwoNumber(int a,int b)            {                return a + b;            }        }
Public delegate int TwoNumberHandleMethodDelegate (int x, int y); the delegate annotation is used to indicate that this is a delegate definition. If delegate is removed and the definition is observed, you will find that this is an abstract method without a method body. So the meaning of the delegate is: the type of the method with the same signature form as the abstract method. A delegate is a new data type that you define. It is the same as int and class. Int indicates an integer. Any integer can be assigned to an int type variable. TwoNumberHandleMethodDelegate indicates this method that receives two int type parameters and returns the int type result, therefore, all methods that meet the preceding requirements can be assigned to variables of the TwoNumberHandleMethodDelegate type.

In this way, the Worker code can be modified:
public class Worker        {            public delegate int TwoNumberHandleMethodDelegate(int x, int y);            public int HandleTwoNumber(int a, int b, TwoNumberHandleMethodDelegate handle)            {                return handle(a, b);            }        }

In this way, operations a and B are encapsulated, and all changes are handled by the caller. Meaning: HandleTwoNumber processes integers a and B. handle implements the processing method. You may ask how to call this method? The call is as follows:

Private static int Add (int a, int B) {return a + B;} private static int Sub (int a, int B) {return a-B ;} static void Main (string [] args) {int a = int. parse (Console. readLine (); int B = int. parse (Console. readLine (); Worker. twoNumberHandleMethodDelegate method = new Worker. twoNumberHandleMethodDelegate (Add); Worker worker = new Worker (); int result = worker. handleTwoNumber (10, 10, method );
// Int result = worker. HandleTwoNumber (10, 10, Sub); // simplified version
            Console.WriteLine(String.Format("Result:{0}", result));
}

According to the above program, the Main code block is the worker caller. As the caller, you should be the most clear about what you want woker to do. Therefore, as the worker of the caller, it only needs to receive the \ B parameter given by the caller Main and execute the algorithm method customized by Main, and then execute the algorithm and return the result. The above code is simple, but it has far-reaching significance. As the programming time increases, I believe that your understanding will become more profound.

In addition to the standard method, delegate variables can also be simplified when being assigned values:

Worker. twoNumberHandleMethodDelegate method = new Worker. twoNumberHandleMethodDelegate (Add); Worker worker = new Worker (); int result = worker. handleTwoNumber (10, 10, method); // it can be simplified to // int result = worker. handleTwoNumber (10, 10, Add );

The compiler will automatically check whether Add complies with the TwoNumberHandleMethodDelegate definition. If yes, assign the method name to the delegate variable directly.

Anonymous Delegation

Through the sample code above, we can easily find that the variable TwoNumberHandleMethodDelegate method is assigned to Add (Sub), so we call method (...) is equivalent to calling Add (.....). In this way, we can think that

Method is exactly the same as Add. Since it is equivalent, can I directly assign the definition content of Add TO THE method variable? The answer is yes:

static void Main(string[] args)        {            Worker.TwoNumberHandleMethodDelegate method =private static int Add(int a, int b)        {            return a + b;        };}

But it is not feasible to pull hard covers like above. You still need to make changes. The modification content is: because the current code is in the Main method, the access modifier should be removed, and static should also be removed; at the same time, the compiler knows that you want to assign a value to the method, the value to be assigned must meet the requirement that the return type is int. All int values are removed at this time, because after the value is assigned, the method is equivalent to Add, you only need to use the method variable for future calls. You do not need to remove all Add method names. The Code becomes in the following format:

static void Main(string[] args)        {            Worker.TwoNumberHandleMethodDelegate method =   (int a, int b)        {            return a + b;        };}

The modification above simplifies a lot, but what is the right side of the method value =? At this time, the compiler does not correctly recognize this method, because the method definition must meet the following requirements: Access slim characters, return type, method name, parameter list, and method body. Although you know that this is a simplified method, the compiler doesn't understand you ........., it doesn't matter if we tell the compiler that the following is a simplified method.

static void Main(string[] args)        {            Worker.TwoNumberHandleMethodDelegate method =   delegate(int a, int b)        {            return a + b;        };}

As you expected, the compiler now knows that = is your simplified method on the right; OK, now you can assign values and use them normally.

Through the above definition, we found that the simplified method marked with delegate does not have a fixed name like Add/Sub. Therefore, we call this method anonymous delegate (I used to call it anonymous ).

You may also notice that after the anonymous delegate definition is complete, it is assigned to the local variable method in the Main code. Therefore, when the method is exceeded, the method will no longer be called. This leads to the most common usage of anonymous methods, anonymous delegation, and anonymous functions, that is, to define functional code that only needs to be used once.

Related Article

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.