Lambda 表达式_CSDN
1. 定义:
Lambda 表达式是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式树类型。
Lambda运算符 =>,该运算符读为“goes to”,Lambda 运算符的左边是输入参数(如果有),右边包含表达式或语句块。
Lambda 表达式返回表达式的结果,并采用以下基本形式:
(input parameters) => expression
只有在 Lambda 有一个输入参数时,括号才是可选的;否则括号是必需的。 两个或更多输入参数由括在括号中的逗号分隔:
(x, y) => x == y
有时,编译器难于或无法推断输入类型。 如果出现这种情况,您可以按以下示例中所示方式显式指定类型:
(int x, string s) => s.Length > x
使用空括号指定零个输入参数:
() => SomeMethod()
在上一个示例中,请注意 Lambda 表达式的主体可以包含方法调用。 但是,如果要创建将在另一个域(比如 SQL Server)中使用的表达式树,则不应在 Lambda 表达式中使用方法调用。 方法在 .NET 公共语言运行时上下文的外部将没有意义。
适用于匿名方法的所有限制也适用于 Lambda 表达式
2. 将此表达式分配给委托类型
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
3. 创建表达式树类型:
using System.Linq.Expressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Expression<del> myET = x => x * x;
}
}
}
4. Lambda 语句
Lambda 语句与 Lambda 表达式类似,只是语句括在大括号中:
(input parameters) => {statement;}
Lambda 语句的主体可以包含任意数量的语句;但是,实际上通常不会多于两个或三个语句。
delegate void TestDelegate(string s);
…
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");
像匿名方法一样,Lambda 语句无法用于创建表达式树。
Lambda 可以引用“外部变量”,这些变量位于在其中定义 Lambda 的封闭方法或类型的范围内。 将会存储通过这种方法捕获的变量以供在 Lambda 表达式中使用,即使变量将以其他方式超出范围或被作为垃圾回收。 必须明确地分配外部变量,然后才能在 Lambda 表达式中使用该变量。
delegate bool D();
delegate bool D2(int i);
class TestLambda
{
D del1;
D2 del2;
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del1 = () => { j = 10; return j > input; };
// del2 will be invoked after TestMethod goes out of scope.
del2 = (x) => {return x == j; };
// Demonstrate value of j:
// Output: j = 0
// The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j);
// Invoke the delegate.
bool boolResult = del1();
// Output: j = 10 b = True
Console.WriteLine("j = {0}.b = {1}", j, boolResult);
}
static void Main()
{
TestLambda test = new TestLambda();
test.TestMethod(5);
// Prove that del2 still has a copy of
// local variable j from TestMethod.
bool result = test.del2(10);
// Output: True
Console.WriteLine(result);
Console.ReadKey();
}
}
浙公网安备 33010602011771号