Home >Backend Development >C#.Net Tutorial >C# Learning Diary 25---Anonymous methods, Func delegates and lambda expressions

C# Learning Diary 25---Anonymous methods, Func delegates and lambda expressions

黄舟
黄舟Original
2017-01-21 15:31:491825browse

In versions of C# prior to 2.0, the only way to declare a delegate was to use a named method. C# 2.0 introduced anonymous methods (delegate), and in C# 3.0 and later, lambda expressions replaced anonymous methods as the preferred way to write inline code.

Anonymous delegate (method):

The name of anonymous delegate is not accurate. The correct name should be called anonymous method (in short, the two mean the same thing). I have mentioned before in Delegate Type that a delegate is used to refer to a method that has the same label as it. In other words, you can use a delegate object to call a method that can be referenced by the delegate (the parameter is the method name). Anonymous methods, on the other hand, take a block of code as a delegate parameter (the parameter is the code that implements the function). By using anonymous methods, you reduce the coding overhead required to instantiate the delegate because you don't have to create a separate method.

Edit anonymous methods:

Whether the anonymous method is directly mounted in the code block within the delegate, or it must be 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 Implement an anonymous method

Anonymous method instance:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test1  
{  
    class Program  
    { //声明一个委托  
        delegate void MyDelegate(string str);   
        //定义一个实名方法  
        public static void fun(string str)    
        {  
            Console.WriteLine("这是一个 {0} 方法", str);  
        }  
        static void Main(string[] args)  
        {  
            //创建一个委托实例,里面包含一个匿名方法  
            MyDelegate examp1 = delegate(string name)   
            {  
              Console.WriteLine("这是一个 {0} 方法",name); //代码块  
            };  
            examp1("匿名");  //调用匿名方法  
  
            MyDelegate examp2 = new MyDelegate(fun); //在委托中实名注册一个fun命名方法  
            examp2("实名");  //调用命名方法  
        }  
    }  
}

Result:

C# Learning Diary 25---Anonymous methods, Func delegates and lambda expressions

The range of parameters of the anonymous method is an "anonymous method block".

It is an error to use jump statements (such as goto, break, or continue) inside an anonymous method block if the target is outside the block. It is also an error to use jump statements (such as goto, break, or continue) outside an anonymous method block if the target is inside the block.

FuncDelegate:

In the past, when we used the delegate delegate, we had to declare a delegate class in advance 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);//声明委托  
        public static string Toup(string str) //定义方法  
        {  
            return str.ToUpper();  
        }  
        static void Main(string[] args)  
        {  
            string str = "abc";  
              
            MyDelegate my = Toup; //注册方法  
            Console.WriteLine(my(str));//调用方法 结果 ABC  
              
        }  
    }  
}

If conditions do not allow us to declare a delegate class in the program, but we need to use a delegate, what should we do? At this point we can consider using the Func delegate. FuncThe last parameter in is the return value type. The previous ones are all the incoming method parameter types. Their functions are similar to delegates, but no declaration is required. The above example is changed to Func delegate:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test1  
{  
    class Program  
    {  
        public static string Toup(string str) //定义方法  
        {  
            return str.ToUpper();  
        }  
        static void Main(string[] args)  
        {  
            string str = "abc";  
  
            Func<string, string> change = Toup; //泛型委托  
            Console.WriteLine(change(str));//调用方法 结果 ABC  
              
        }  
    }  
}

In comparison, the results of the two are the same, but Func is much simpler than Delegate, but Delegate can load anonymous methods. For example, in 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);//声明委托  
  
        static void Main(string[] args)  
        {  
            string str = "abc";  
            //创建匿名方法  
            MyDelegate my = delegate(string s) { return s.ToUpper(); };   
            Console.WriteLine(my(str)); //结果 ABC  
              
        }  
    }  
}

Can Func also work? Func can also create anonymous methods, and there is no need to declare them, 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";  
            //创建匿名方法  
            Func<string, string> change = delegate(string s) { return s.ToUpper(); };  
            Console.WriteLine(change(str)); //结果 ABC  
              
        }  
    }  
}

Compared with the above anonymous methods, we find that when creating anonymous methods, both are implemented through delegates (or Delegate is used), can I not use delegate? It is okay not to use it. At this time we need to learn lambda expression

lambda expression:

Lambda expression is An anonymous method that can be used to create a delegate or expression tree type. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of a function call. To create a Lambda expression, you specify the input parameters (if any) on the left side of the Lambda operator => and then enter an expression or block of statements on the other side. For example, the lambda expression x => x * x specifies an argument named x and returns the square of x .


So in the above example, we use lambda expression to create an anonymous method and change it to:

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 表达式  
            Func<string, string> change = s => s.ToUpper(); //传入string 类型s 返回s.ToUpper();  
            Console.WriteLine(change(str)); //结果 ABC  
              
        }  
    }  
}

In the delegate delegate type, we can also use lambda expression Create anonymous methods:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test1  
{  
    class Program  
    {  
        delegate string MyDelegate(string s);//声明委托  
  
        static void Main(string[] args)  
        {  
            string str = "abc";  
            //lambda 表达式  
            MyDelegate my = s => s.ToUpper(); //传入string 类型s 返回s.ToUpper();  
            Console.WriteLine(my(str)); //结果 ABC  
              
        }  
    }  
}

The above is the content of C# Learning Diary 25---Anonymous methods, Func delegates and lambda expressions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn