The forms of lambda expressions

本文深入探讨了C#中的Lambda表达式,包括参数传递方式、返回值类型匹配及表达式主体等内容。此外,还讨论了变量作用域、外部变量访问等特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

x=>x*x;//A simple expression that returns the square of its parameter. The type of parameter x is inferred from the context.
x=>{return x*x;};// Semantically the same as the preceding. expression, but using a c# statement block as a body rather than a simple expression.
(int x)=>x/2;//A simple expression that returns the value of the parameter divided by 2. The type of parameter x is stated explicitly.
()=>folder.StopFolding(0);//Calling a method. The expression takes no parameters. The expression might or might not return a value.
(x,y)=>{x++;return x/y;}//Multiple parameters; the compiler infers the parameter types. The parameter x is passed by value. so the effect of the ++ operation is local to the expression.
(ref int x,int y)=>{x++;return x/y;}//Multiple parameters with explicit types Parameter x is passed by reference, so the effect of the ++ operation is permanent.

If a lambda expression takes parameters, you specify them in the parentheses to the left of the => operator. You can omit the types of parameters, and the c# compiler will infer their types from the context of the lambda expression. Yor can pass parameters by reference(by using the ref keyword)if you want the lambda expression to be able to change its values other than locally, but this is not recommended.
Lambda expressions can return values, but the return type must match that of the delegate to which thye are being added.
The body of a lambda expression can be a simple expression or a block of c# code made up of multiple statements, method calls, variable definitions, and other code items.
Variables defined in a lambda expression method go out of scope when the method finishes.
A lambda expression can access and modify all variables outside the lambda expression that are in scope when the lambda expression is defined. Bevery carful with this feature!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值