Specific descriptions of delegates and anonymous delegates in C #

Source: Internet
Author: User
Tags define function
This article mainly for you to introduce the C # delegation and anonymous delegation of relevant information, with a certain reference value, interested in small partners can refer to

Originally wanted to write a "delegate and lambda expression of the past life", but only the delegate part has written a lot of content, so separate about the lambda expression is the content of the subsequent write it.

I don't know who invented the lambda expression, just remember that the first contact with the lambda expression is in the use of VS2008, it was invented by Microsoft first.

Lambda expressions from the beginning of my contact began to become more and more popular, Java8 in the beginning of support, Kotlin is the c#,f# to do a wide range of plagiarism (C # has not been such a time to treat Java). In fact, this fully illustrates the importance of lambda expressions. The first thing to figure out is that lambda needs to know the delegate.

Commissioned:

Suppose now we are going to develop a program that processes two integers (assuming that the add operation is processed first)


public class Worker {//<summary>//////////////      <param name= "a" ></param>//      <param name= "B" ></param>//      <returns></returns>      public int handletwonumber (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 worker = new Worker ();      int result = worker. Handletwonumber (A, b);      Console.WriteLine (String.Format ("result:{0}", Result));      String p = Console.ReadLine ();}

If after some time, we need it to be changed to minus operation:


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

Although there is a slight change in the a+b to a-B, there may be several changes in the following (from minus to ...). )。 Change should encapsulate change, where we can abstract the operation of A and B, with what abstraction? Commissioned


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); here is a delegate callout indicating that this is a delegate definition. If you remove delegate and then look at the definition, 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 form as the abstract method signature. A delegate is a new type of data that you define, which is the same as int, class, and is the data type. int is an integer, as long as an integer can be assigned to an int variable, Twonumberhandlemethoddelegate is a method that receives two int parameters and returns the result of the int type. Therefore, the methods that meet the above requirements can be assigned to variables of type twonumberhandlemethoddelegate.

As a result, the worker code can be modified to:


public class Worker    {public      delegate int twonumberhandlemethoddelegate (int x, int y);      public int Handletwonumber (int a, int b, twonumberhandlemethoddelegate handle)      {        return handle (A, b);      }    }

So the operations of A and B are encapsulated, and all changes are referred to the caller for processing. Here's what it means: Handletwonumber handles A, b two integers, specifically how to handle the implementation by handle. At this point you may ask, how do you call the 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-a      ;    }    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 (ten, 10,method); int result = worker. Handletwonumber (ten, Sub);//Simplified version      Console.WriteLine (String.Format ("result:{0}", Result);}

According to the above procedure, the main block is the caller of the worker and, as the caller, should be the most aware of the work that they want Woker to do. Therefore, as the worker of the callee, it only needs to receive the a\b parameter given by the caller main and the algorithm method that executes the main custom, and then follow the algorithm and return the result. Although the above code is simple, it has a profound meaning, and as the programming time increases, you will understand the deeper.

Delegate variables can be simplified in addition to the standard way they are assigned:


Worker.twonumberhandlemethoddelegate method = new Worker.twonumberhandlemethoddelegate (ADD);      Worker worker = new Worker ();      int result = worker. Handletwonumber (10,method);//Can be simplified to//int result = worker. Handletwonumber (ten, 10,add);

The compiler automatically checks to see if add conforms to the definition of twonumberhandlemethoddelegate, and if it conforms to allow direct assignment of the method name to the delegate variable.

Anonymous delegate

With the example code above, it is easy to see that the Twonumberhandlemethoddelegate method variable is assigned the Add (Sub), so the method (...) is called. is equivalent to calling Add (...). So that you can think

The method is exactly equivalent to add, and since it is equivalent, is it possible to assign the definition of add to the method variable directly? The answer is yes:


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

But like this kind of life to pull a hard sleeve is not possible, you need to make changes. The modification is: Because the code is now in the main method, the access modifier is removed, the same static should be removed, and the compiler knows you want to assign a value to the method, then the value to be assigned must satisfy the return type of int, all int at this time is superfluous to remove Because the method is equivalent to add after the assignment, subsequent calls can be done with the method variable, and all the Add method names do not need to be removed. So the code changes to the following form:


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

The above modification simplifies a lot, but what is the value of method assignment = right-hand thing? At this point the compiler does not correctly recognize this as a method, because the definition of the method needs to satisfy the inclusion: access to the character, return type, method name, parameter list, method body five parts. Although you know that this is a simplified method, but the compiler does not understand your heart ..., that's okay. As long as we tell the compiler, the following is a simplified method.


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

As you would expect, now the compiler knows that the right side is your simplified method; ok, now it can be assigned and used correctly.

Through the above definition we find that the simplified method of labeling with delegate does not have a name as fixed as add/sub. So we call this method an anonymous delegate (I'm used to calling it an anonymous method).

You may also notice that the anonymous delegate is defined so that it is assigned to the local variable method, which is fast in the main code, so that the method has no chance of being called when it is outside the scope of method. This leads to the most common use of anonymous methods, anonymous delegates, anonymous functions, which define function 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.