表达式主体成员与 Lambda 表达式 [英] Expression-bodied members vs Lambda expressions

查看:76
本文介绍了表达式主体成员与 Lambda 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lambda 表达式是被视为对象的代码块(表达式或语句块).它可以作为参数传递给方法,也可以通过方法调用返回.

A lambda expression is a block of code (an expression or a statement block) that is treated as an object. It can be passed as an argument to methods, and it can also be returned by method calls.

(input parameters) => expression
 SomeFunction(x => x * x);

看着这个语句,我想知道使用 lambdas 和使用 Expression-bodied 时有什么区别?

Looking this statement I was wondering what's the difference when using lambdas and when using Expression-bodied?

public string Name => First + " " + Last;

推荐答案

表达式体方法是语法糖.而不是写这个:

Expression bodied methods are syntactic sugar. Instead of writing this:

public string GetName()
{
    return First + " " + Last;
}

你可以这样写:

public string GetName() => First + " " + Last;

调用第一个或第二个的结果将完全相同.

and the result of calling either the first or the second would be exactly the same.

同样适用于所有类型的 表达式主体成员.

The same is true also for all the kinds of expression body members.

另一方面,一个 lambda 表达式,正如它正式声明的那样 这里 是:

On the other hand, a lambda expressions as it is stated formally here is:

一个匿名函数,您可以使用它创建委托或表达式树类型.

an anonymous function that you can use to create delegates or expression tree types.

话虽如此,很明显,尽管语法相似,但有两种完全不同的东西.

That being said it is clear that despite the similarity in syntax, there are two completely different things.

这篇关于表达式主体成员与 Lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆