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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There are multiple ways of expressing lambdas, depending on the exact scenario - some examples:
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)
You can use lambdas without arguments by using an empty expression list:
Ideally, the expression on the right hand side is exactly that; a single expression. The compiler can convert this to either a
delegate
or anExpression
tree:However; you can also use statement blocks, but this is then only usable as a
delegate
: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 simpleExpression
trees unless you do it "the hard way"; see my article on InfoQ for more information.A lambda expression is, fundamentally, a shorthand notation for a function pointer. More commonly, a lambda expression is the propagation of input data into an expression that computes a result. In most cases, you will use lambda expressions in their more common form:
In their less common form, lambda expression can replace more cumbersome delegate forms:
Or the less common, and less verbose:
The following lambda expression achieves the same result as the above two:
The power of this latter form really comes from its capability to create closures. A closure is where you implement a function within a function, and "close" around parameters and variables from the parent function scope: