有多种表达 lambda 的方法,具体取决于具体场景 - 一些示例:
// simplest form; no types, no brackets
Func<int, int> f1 = x => 2 * x;
// optional exlicit argument brackets
Func<int, int> f2 = (x) => 2 * x;
// optional type specification when used with brackets
Func<int, int> f3 = (int x) => 2 * x;
// multiple arguments require brackets (types optional)
Func<int, int, int> f4 = (x, y) => x * y;
// multiple argument with explicit types
Func<int, int, int> f5 = (int x, int y) => x * y;
lambda 的签名必须与所使用的委托的签名相匹配(无论是显式的,如上面,还是由上下文隐含的,例如.Select(cust => cust.Name)
您可以使用 lambdawithout使用空表达式列表的参数:
// no arguments
Func<int> f0 = () => 12;
理想情况下,右侧的表达式正是如此;一个单一的表达。编译器可以将其转换为either a delegate
or an Expression
tree:
// expression tree
Expression<Func<int, int, int>> f6 = (x, y) => x * y;
然而;您还可以使用语句块,但这只能用作delegate
:
// braces for a statement body
Func<int, int, int> f7 = (x, y) => {
int z = x * y;
Console.WriteLine(z);
return z;
};
请注意,即使 .NET 4.0Expression
树支持语句体,C# 4.0 编译器doesn't为您执行此操作,因此您仍然仅限于简单的Expression
树木,除非你采取“艰难的方式”;看我在 InfoQ 上的文章 http://www.infoq.com/articles/expression-compiler了解更多信息。