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 an anonymous method (delegate), and in C # 3.0 and later, LAMBDA expressions replace anonymous methods as the preferred way to write inline code. Anonymous Delegate (method):

Anonymous delegation is not an accurate term, it should be called anonymous method, (in short the two 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); //Declare a delegate

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

Anonymous method instances:
Using system;using system.collections.generic;using system.linq;using system.text;namespace Test1{    class Program    {//declares 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 containing an anonymous method            mydelegate examp1 = Delegate (string name)             {              Console.WriteLine ("This is a {0} method", name);//code block            };            EXAMP1 ("anonymous");  Call the anonymous method            mydelegate examp2 = new MyDelegate (fun);//Register a fun naming method            examp2 ("real name")  in the delegate. Call the Named 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);//Declaration delegate public        static string Toup (String str)//Definition 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 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);//declaration 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)); Results 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";            Create an anonymous method            func<string, string> change = Delegate (string s) {return s.toupper ();};            Console.WriteLine (Change (str)); Results ABC                    }}}    


compared to the anonymous method above, we find that both are implemented by delegate when creating anonymous methods ( or delegate), can we not delegate without it, then we need to learn lambda An 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 ();//incoming string type S returns S. ToUpper ();            Console.WriteLine (Change (str)); Results 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);//declaration 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)); Results ABC                    }}}    


Thank you for your reading and welcome your suggestions and comments ^_^

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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

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.