Lambda 表达式(C# 编程指南)

Lambda 表达式是一种可用于创建委托表达式目录树类型的匿名函数通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数。  Lambda 表达式对于编写 LINQ 查询表达式特别有用。 

若要创建 Lambda 表达式,需要在 Lambda 运算符 => 左侧指定输入参数(如果有),然后在另一侧输入表达式或语句块。例如,lambda 表达式 x => x * x 指定名为 x 的参数并返回 x 的平方值。  如下面的示例所示,你可以将此表达式分配给委托类型:

        delegate int del(int i);
        static void Main(string[] args)
        {
            del myDelegate = x => x * x;
            //等同于
            del myDelegate = new del(Square);

            int j = myDelegate(5); //j = 25
        }

        private static int Square(int x)
        {
            return x * x;
        }
  • 语句Lambda
1 delegate void TestDelegate(string s);
2 3 TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
4 myDel("Hello");
原文地址:https://www.cnblogs.com/tuqun/p/3736444.html