匿名函数:Lambda表达式和匿名方法

匿名函数一个“内联”语句或表达式,可在需要委托类型的任何地方使用。可以使用匿名函数来初始化命名委托,或传递命名委托(而不是命名委托类型)作为方法参数。

共有两种匿名函数:

Lambda表达式(在这里只举例在Lambda表达式在委托中的应用)

匿名方法 

Lambda表达式是一种可用于创建委托表达式目录树(以后再讨论)类型的匿名函数。通过使用Lambda表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数。

若要创建Lambda表达式,需要在Lambda运算符 =>左侧指定输入参数(如果有),然后在另一侧输入表达式或语句块。

看一个例子:

        delegate int del(int i);
        static void Main(string[] args)
        {
            //Lambda表达式用于创建委托
            del myDelegate = x => x * x;
            int j = myDelegate(5);
            Console.WriteLine(j);
        }

(input parameters)=>expression

仅当Lambda只有一个输入参数时,括号才是可选的;否则括号是必须的。括号内的两个或更多输入参数使用逗号加以分割:

(x, y)=>x==y

有时,编译器难以或无法推断输入类型,如果这种出现这种情况,你可以显示指定类型:

(int x, string s)=>s.length>x

使用空括号指定领个输入参数:

( )=>SomeMethod()

语句Lambda

语句Lamdba与表达式Lambda表达式类似,只是语句括在大括号中:

( input parameters ) => { statement ;}

看一个例子:

        delegate void TestDelegate(string s);
        static void Main(string[] args)
        {
            //Lambda语句用于创建委托
            TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
            myDel("Hello");
        }

匿名方法

在2.0之前的C#版本中,声明委托的唯一方法是使用命名方法。C# 2.0引入了匿名方法,而在C# 3.0及更高版本中,Lambda表达式取代了匿名方法,作为编写内联代码的首先方式。

看一个例子:

        delegate void Printer(string s);
        static void Main(string[] args)
        {
            //委托与匿名方法关联
            Printer p = delegate (string st)
              {
                  Console.WriteLine(st);
              };
            p("The delegate using the anonymous method is called.");

            //委托与命名方法关联
            p = new Printer(DoWork);
            p("The delegate using the named method is called.");
            Console.ReadKey();
        }
        static void DoWork(string k)
        {
            Console.WriteLine(k);
        }
原文地址:https://www.cnblogs.com/xiao9426926/p/5972304.html