匿名方法(C#2.0)和lambda表达式(C#3.0)有什么区别?

问题描述:

C#2.0的 匿名方法 与C#3.0的 lambda表达式 之间有什么区别? / p>

What is the difference between anonymous methods of C# 2.0 and lambda expressions of C# 3.0.?

匿名方法的MSDN页面解释了它


在2.0之前的C#版本中,唯一的
方式声明一个委托是使用
命名方法。 C#2.0引入了
匿名方法,而在C#3.0和
之后,lambda表达式取代
匿名方法作为首选方式
来编写内联代码。但是,
中的匿名方法的
信息也适用于lambda
表达式。在
中有一种情况,匿名方法提供
表达式中没有找到的
功能。匿名方法使
可以省略参数列表,而
这意味着匿名方法
可以转换为具有
各种签名的代理。这不是λb $ b可能与lambda表达式。有关
的更多信息,具体涉及
lambda表达式,请参阅Lambda
表达式(C#编程指南)。

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list, and this means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide).

关于lambda表达式


lambda表达式是一个可以包含表达式和语句的匿名函数,可用于创建委托或表达式树类型。
所有lambda表达式使用lambda操作符=>,它被读为转到。 lambda运算符的左侧指定输入参数(如果有),右侧保存表达式或语句块。 lambda表达式x => x * x被读取为x转到x乘以x。此表达式可以分配给一个委托类型,如下所示:

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows: