Take you through the C # delegate, anonymous method, Lambda, generic delegate, expression tree code example

Source: Internet
Author: User
take you through the C # delegate, anonymous method, Lambda, generic delegate, Expression tree code example:





These are old-age programmers are commonplace, nothing new, the new generation of programmers is full of charm. Once the new generation, many have been through a long learning, understanding, practice to master the delegation, expression tree these applications. Today I try to describe it in a simple way, so that you will be finished with this blog in five minutes.






First minute: Delegate



Some textbooks, the blog said the Commission will refer to events, although the event is an example of the delegation, but in order to understand the simpler, today only talk about the commission of the event. The first piece of code:



The code below completes a demo of the delegate application. A delegate is divided into three steps:


Public partial class WebForm3 : System.Web.UI.Page

{

     //step01: First define a delegate with delegate.

     Public delegate int CalculatorAdd(int x, int y);

 

     Protected void Page_Load(object sender, EventArgs e)

     {

         //step03: Use this method to instantiate this delegate.

         CalculatorAdd cAdd = new CalculatorAdd(Add);

         //int result = cAdd(5, 6);

         Int result = cAdd.Invoke(5,6);

     }

     // step02: Declare a method to correspond to the delegate.

     Public int Add(int x, int y)

     {

         Return x + y;

     }

}


STEP01: First define a delegate with delegate.



STEP02: Declares a method to correspond to a delegate.



STEP03: Use this method to instantiate the delegate.



At this point, a delegate should be completed, you can invoke the delegate.



Second minute: Anonymous method



In the last minute already know, complete a commissioned application in three steps to go, lack of one step is not, if you want to stride, beware of the pace of the big pull the egg. But Microsoft is not afraid to pull the egg, must take three steps to make two steps to go! So Microsoft is using an anonymous method to simplify the top three steps. Anonymous method How to say this thing, in C # is absolutely dispensable things, just for C # icing on the cake, some ingenuity to give it a name called Grammar sugar.


Public partial class WebForm3 : System.Web.UI.Page

{

     //step01: First define a delegate with delegate

     Public delegate int CalculatorAdd(int x, int y);

 

     Protected void Page_Load(object sender, EventArgs e)

     {

         //step02: Assign a method to the delegate with this method delegate(int x, int y) { return x + y; }

         CalculatorAdd cAdd = delegate(int x, int y) { return x + y; };

         Int result = cAdd.Invoke(5, 6);

     }

}



STEP01: First define a delegate with delegate.



STEP02: Using this notation delegate (int x, int y) {return x + y;}, assigning a method to a delegate is actually an anonymous method.



It is surprising to find that this is not the three steps in front of the two steps to go wow?



Third minute: lambda expression



Originally very simple program, plus a few delegate keywords, this code will become abstruse, esoteric things understand people will become less, so this can also be used as a bargaining chip. But Microsoft's design philosophy for C # is simple and easy to use. Microsoft is trying to simplify delegate (int x, int y) {return x + y;} This anonymous method, lambda appears. Let me look at several lambda expressions:


Public partial class WebForm3 : System.Web.UI.Page

{

     Public delegate int CalculatorAdd(int x, int y);

 

     Protected void Page_Load(object sender, EventArgs e)

     {

         //method one:

         CalculatorAdd cAdd1 = (int x, int y) => { return x + y; };

         Int result1 = cAdd1(5, 6);

 

         //Method Two:

         CalculatorAdd cAdd2 = (x, y) => { return x + y; };

         Int result2 = cAdd2(5, 6);

 

         / / Method three:

         CalculatorAdd cAdd3 = (x, y) => x + y;

         Int result3 = cAdd2(5, 6);

     }

}



Method One: Simply remove the delegate and add "=" between () and {}.



Method Two: The parameter types are eliminated on the basis of method one.



Method Three: To do a thorough job, the {}, as well as the return keyword is removed.



These kinds of methods can be any way to write, but it is to harm the beginner, a moment to see this style, a moment to see that style, the people engaged in the fascination of people, if no one pointing, it will be confused, difficult to be here.



Four minute: generic delegate



With the. NET version of the non-upgrade, the new version will always be different from the old version of it, or how Microsoft engineers to their boss? So Microsoft has come to play tricks again.


Public partial class WebForm3 : System.Web.UI.Page

{

     Protected void Page_Load(object sender, EventArgs e)

     {

         //method one:

         Func<int,int,int> cAdd1 = (int x, int y) => { return x + y; };

         Int result1 = cAdd1(5, 6);

 

         //Method Two:

         Func<int, int, int> cAdd2 = (x, y) => { return x + y; };

         Int result2 = cAdd2(5, 6);

 

         / / Method three:

         Func<int, int, int> cAdd3 = (x, y) => x + y;

         Int result3 = cAdd2(5, 6);

     }

}



Whether it is an anonymous method or a lambda expression, the application of a delegate cannot escape two steps, one step is to define a delegate, and the other is to instantiate a delegate with a method. Microsoft simply took the two steps to the next step to go. Use Func to simplify the definition of a delegate.



At this point the application of a delegate can be func<int, int, int> CADD3 = (x, y) + x + y; This is a sentence to complete, wherein the func is the so-called generic delegate.



Five minutes: expression tree



The expression tree actually has nothing to do with the delegate, it has to be related, so to speak, the expression tree is the container that holds the delegate. If you want to speak more professionally, an expression tree is a data structure that accesses lambda expressions. To use a lambda expression, get it directly from the expression, Compile () can be used directly. The following code:



public partial class WebForm3 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        Expression<Func<int, int, int>> exp = (x, y) => x + y;

        Func<int, int, int> fun = exp.Compile();

        int result = fun(2, 3);

    }

}




What I ordered is superficial, but at least let's review a delegate, anonymous method, Lambda, generic delegate, expression tree.


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.