Lambda表达式通用语法 [英] Lambda expression common syntax
问题描述
我可以遵循任何简单的synax或规则在C#中构建"lambda表达式"吗?我读了一些文章并了解了lambda表达式是什么,但是如果我有通用的语法或规则会有所帮助.
Can I follow any simple synax or rules for building "lambda expression" in C#? I read some articles and understood what a lambda expression is, but if I have the general syntax or rules that would be helpful.
推荐答案
根据具体情况,有多种表达lambda的方法-一些示例:
There are multiple ways of expressing lambdas, depending on the exact scenario - some examples:
// 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)
The signature of the lambda must match the signature of the delegate used (whether it is explicit, like above, or implied by the context in things like .Select(cust => cust.Name)
您可以通过使用一个空的表达式列表来使用不带参数的lambdas :
You can use lambdas without arguments by using an empty expression list:
// no arguments
Func<int> f0 = () => 12;
理想情况下,右侧的表达正是这样;单个表达式.编译器可以将其转换为 delegate
或 Expression
树:
Ideally, the expression on the right hand side is exactly that; a single expression. The compiler can convert this to either a delegate
or an Expression
tree:
// expression tree
Expression<Func<int, int, int>> f6 = (x, y) => x * y;
但是;您也可以使用语句块,但这只能用作delegate
:
However; you can also use statement blocks, but this is then only usable as a delegate
:
// braces for a statement body
Func<int, int, int> f7 = (x, y) => {
int z = x * y;
Console.WriteLine(z);
return z;
};
请注意,即使.NET 4.0 Expression
树支持语句主体,但C#4.0编译器不会为您执行此操作,因此除非另有说明,否则您仅限于简单的Expression
树您以艰难的方式"做到;有关更多信息,请参见我在InfoQ上的文章.
Note that even though the .NET 4.0 Expression
trees support statement bodies, the C# 4.0 compiler doesn't do this for you, so you are still limited to simple Expression
trees unless you do it "the hard way"; see my article on InfoQ for more information.
这篇关于Lambda表达式通用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!