A detailed explanation of the use of anonymous delegates and lambda expressions in C #

Source: Internet
Author: User
This article mainly for you in detail the C # Anonymous delegate and lambda expression related data, with a certain reference value, interested in small partners can refer to

Make programming more flexible by using anonymous delegates (anonymous methods), and refer to my previous blog, delegate and anonymous delegation, for delegates and anonymous delegates.

To continue the previous example, the code is as follows:


static void Main (string[] args) {   Worker.twonumberhandlemethoddelegate method = delegate (int a, int b)  {   return a + B;  };   Worker worker = new Worker ();   int result = worker. Handletwonumber (ten, 10,method);   Console.WriteLine (String.Format ("result:{0}", Result));   Console.ReadLine ();}

The above program worker will calculate the result return according to the parameter and calculation method given by main. According to the equivalence code can be further simplified, as follows:


static void Main (string[] args)  {   worker worker = new Worker ();   int result = worker. Handletwonumber (Ten, delegate (int a, int b)   {    return a + b;   });   Console.WriteLine (String.Format ("result:{0}", Result));   Console.ReadLine ();  }

See here have JS, jquery development experience of friends may be sudden feeling cordial, oh ... anonymous function. $ ("#id") that is used everywhere in jquery. Click (function () {...}).

In C #, the use of anonymous delegates can be further streamlined, and the resulting refinement becomes an expression called a lambda expression.


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

Lambda expression representation:


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

C # lambda expressions are divided into two parts, (A, b) as a parameter list, {...}, using =. As the method body.


static void Main (string[] args)  {   worker worker = new Worker ();   int result = worker. Handletwonumber (Ten, (A, b) = =   {    return a + b;   });   Console.WriteLine (String.Format ("result:{0}", Result));   Console.ReadLine ();  }

The following method is compared to the lambda expression conversion


private void A1 ()    {      Console.WriteLine ("....");    } Lambda () =>{console.writeline ("....");};/ /If the method body code has only one sentence, as above can also omit the method body brace () =>console.writeline ("...");


private string A2 (int a, int b)    {      return String.Format ("{0}+{1}={2}", A, B, a + B);    }    As the example above can be simplified to    (A, a) =>{return String.Format ("{0}+{1}={2}", A, B, a + b);}    Because the method body has only one sentence, can be further simplified    (A, a) = String.Format ("{0}+{1}={2}", A, B, a + B);    Notice that the return should be removed, and the C # compiler automatically recognizes = = To do the return value


private string A3 (int a)    {      return String.Format ("{0}", a);    }    The example above can be simplified to    (a) =>string.format ("{0}", a);    If the parameter list has only one parameter, the () parameter list can be removed, which is further simplified to    a=>string.format ("{0}", a);

With this article you may have realized that in C #, methods, delegates, anonymous methods, lambda expressions do not distinguish boundaries clearly, and they can be flexibly transformed. In actual development, there are many knowledge points about delegates, such as delegates and events. If time permits, I hope to be able to write the article of the deepening of the delegation.

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.