Lambda 表达式是一个匿名函数,是C# 3.0引入的新特性。Lambda 运算符=>,该运算符读为“goes to”。C#为委托提供一种机制,可以为委托定义匿名方

法,匿名方法没有名称,编译器会定指定一个名称。匿名方法中不能使用跳转语句跳转到该匿名方法的外部,也不能跳转到该方法的内部。也不能在匿名方法外部

使用的ref和out参数。


下面的代码简单的演示了Lambda表达式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions; //using

namespace Lambda
{
class Program
{
//委托方法
delegate string MyDelagate(string val);

static void Main(string[] args)
{
string str1 = "匿名方法外部\n";

//中括号部分定义了一个方法,没有名称,编译器会自动指定一个名称
MyDelagate my = (string param) =>
{
string str2 = "匿名方法内部\n";
return(param + str1 + str2);
};

//调用委托的匿名方法
Console.WriteLine(my("参数\n"));

//从结果可以看到,匿名方法同样达到了为委托定义实现体方法的效果
Console.Read();
}
}
}


λ运算符 =>

左边是参数,使用括号表达 (string param),

右边是实现代码,使用花括号,如果代码只有一行,则不使用花括号和return关键字也可以,编译器会为我们添加。

这是λ表达式的简单实现:

string str1 = " 匿名方法外部 ";
string str2 = " 匿名方法内部 ";
MyDelagate my = param => param + str1 + str2;
Console.WriteLine(my(" 参数 "));


1个参数:

private delegate int MyDelagate(int i);

MyDelagate test1 = x => x * x;
MyDelagate test2 = (x) => x * x;
MyDelagate test3 = (int x) => x * x;
MyDelagate test4 = (int x) => { return x * x; };

Console.WriteLine(test1(10));
Console.WriteLine(test2(10));
Console.WriteLine(test3(10));
Console.WriteLine(test4(10));


2个或多个参数:两个或者多个参数不能使用简略的方式书写,必须使用小括号声明参数。

private delegate int MyDelagate(int x, int y);

MyDelagate test1 = (x, y) => x * y;
MyDelagate test2 = (int x, int y) => x * y;
MyDelagate test3 = (int x, int y) => { return x * y; };

Console.WriteLine(test1(3,4));
Console.WriteLine(test2(3,4));
Console.WriteLine(test3(3,4));


无参数:


private delegate void Void();       

void test11 = () => { Console.WriteLine("Void Params"); };
test11();