C # Learning Diary---Anonymous method with func delegate and lambda expression

Source: Internet
Author: User





In the C # version prior to 2.0, the only way to declare a delegate was to use a named method. C # 2.0 introduces anonymous methods (delegates), whereas in C # 3.0 and later, LAMBDA expressions supersede anonymous methods as the preferred way to write inline code.






Anonymous delegate (method):



The anonymous delegate is not exactly what it should be, it should be called an anonymous method (in short, it is a meaning). As I have already mentioned in the preceding delegate type, the delegate is used to refer to the method with the same label. In other words, you can use a delegate object to invoke a method that can be referenced by a delegate (the parameter is the method name). The anonymous method is to use the anonymous method by using the code block as the delegate parameter (the parameter is the code that implements the function), because you do not have to create a separate method, thus reducing the coding overhead required to instantiate the delegate.






To edit an anonymous method:



An anonymous method is a block of code that is mounted directly within a delegate, or declared by using the delegate keyword to create a delegate instance.



delegate void MyDelegate (int i); Declaring a delegate



MyDelegate my = delegate (int i) {/* code block */}; Implement an anonymous method by creating a delegate instance






Anonymous method instances:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     { //Declare a delegate

         Delegate void MyDelegate(string str);

         / / Define a real name method

         Public static void fun(string str)

         {

             Console.WriteLine("This is a {0} method", str);

         }

         Static void Main(string[] args)

         {

             / / Create a delegate instance, which contains an anonymous method

             MyDelegate examp1 = delegate(string name)

             {

               Console.WriteLine("This is a {0} method", name); //code block

             };

             Ex exam1 ("anonymous"); / / call anonymous method

   

             MyDelegate examp2 = new MyDelegate(fun); //Register a fun naming method in the delegate name

             Ex examp2 ("real name"); / / call the naming method

         }

     }

}


Results:






The parameters of an anonymous method are scoped to the anonymous method block.



If the target is outside the block, it is an error to use a jump statement (such as Goto, break, or continue) within an anonymous method block. If the target is inside a block, it is also an error to use a jump statement (such as Goto, break, or continue) outside the anonymous method block.






Func<t,tresult> Commission:



Previously we had to declare a delegate class in advance using the delegate delegate, and then register the method with the delegate, such as:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     {

         Delegate string MyDelegate(string s);//Declare delegate

         Public static string Toup(string str) //Define the method

         {

             Return str.ToUpper();

         }

         Static void Main(string[] args)

         {

             String str = "abc";

               

             MyDelegate my = Toup; //Registration method

             Console.WriteLine(my(str));//call method result ABC

               

         }

     }

}


What if the condition does not allow us to declare the delegate class in the program, but we need to use the delegate? At this point we can consider using the Func delegate. Func<string,string> the last parameter in <> is the return value type, preceded by the incoming method parameter type, which is similar to the delegate, but does not need to be declared, the above example changed to the Func delegate:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     {

         Public static string Toup(string str) //Define the method

         {

             Return str.ToUpper();

         }

         Static void Main(string[] args)

         {

             String str = "abc";

   

             Func<string, string> change = Toup; //generic delegate

             Console.WriteLine(change(str));//call method result ABC

               

         }

     }

} 


In contrast, the results are the same, but Func is a lot more concise than delegate, but delegate can load anonymous methods, such as the above example we use anonymous methods:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     {

         Delegate string MyDelegate(string s);//Declare delegate

   

         Static void Main(string[] args)

         {

             String str = "abc";

             / / Create an anonymous method

             MyDelegate my = delegate(string s) { return s.ToUpper(); };

             Console.WriteLine(my(str)); //Result ABC

               

         }

     }

}


is func okay? Func can also create anonymous methods, and the same does not need to be declared, as follows:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;



Namespace Test1

{

Class Program

{

Static void Main(string[] args)

{

String str = "abc";

//lambda expression

Func<string, string> change = s => s.ToUpper(); //input string type s returns s.ToUpper();

Console.WriteLine(change(str)); //Result ABC



}

}

}


Compared to the anonymous method above, we found that when creating an anonymous method, both are implemented through delegate (or delegate), can not be delegate, without it is possible, then we need to learn the lambda expression






Lambda expression:



A LAMBDA expression is an anonymous method that you can use to create a delegate or an expression tree type. By using a lambda expression, you can write a local function that can be passed as a parameter or returned as a function call value. To create a lambda expression, you specify an input parameter, if any, on the left side of the lambda operator, and then enter the expression or statement block on the other side. For example, the lambda expression x = = X * x refers to the parameter named X and returns the square value of x.






So the above example we use a lambda expression to create an anonymous method instead:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     {

         Static void Main(string[] args)

         {

             String str = "abc";

             //lambda expression

             Func<string, string> change = s => s.ToUpper(); //input string type s returns s.ToUpper();

             Console.WriteLine(change(str)); //Result ABC

               

         }

     }

}


In the delegate delegate type, we can also create an anonymous method using a lambda expression:


Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

   

Namespace Test1

{

     Class Program

     {

         Delegate string MyDelegate(string s);//Declare delegate

   

         Static void Main(string[] args)

         {

             String str = "abc";

             //lambda expression

             MyDelegate my = s => s.ToUpper(); //Incoming string type s returns s.ToUpper();

             Console.WriteLine(my(str)); //Result ABC

               

         }

     }

}


The above is the C # Learning Diary---Anonymous method and the contents of the Func delegate and lambda expression, for more information please follow topic.alibabacloud.com (www.php.cn)!


  • 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.