我刚刚在本论坛的一些问题中遇到了这种语法,但 Google 和任何其他搜索引擎往往会在搜索中屏蔽除字母和数字之外的任何内容,因此无法搜索到=>".
那么谁能告诉我它是什么以及它是如何使用的?
解决方案这是 lambda 运算符.
从 C# 3 到 C# 5,这仅用于 lambda 表达式.这些基本上是 C# 2 中引入的 匿名方法 的较短形式,但也可以转换为表达式树.
举个例子:
FuncnameProjection = p =>p.姓名;相当于:
FuncnameProjection = 委托 (Person p) { return p.Name;};在这两种情况下,您都使用 Person 参数创建委托,返回该人的姓名(作为字符串).
在 C# 6 中,相同的语法用于 表达式主体成员,例如
//表达式体属性public int IsValid =>名称 != null &&id != -1;//表达式体方法public int GetHashCode() =>id.GetHashCode();另见:
- 有什么区别匿名方法 (C# 2.0) 和 lambda 表达式 (C# 3.0) 之间的区别
- 什么是 Lambda?
- C# Lambda 表达式,我为什么要使用它?
(确实有许多类似的问题 - 试试 lambda 和 lambda-expressions 标签.)
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>".
So can anyone tell me what it is and how it is used?
解决方案It's the lambda operator.
From C# 3 to C# 5, this was only used for lambda expressions. These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees.
As an example:
Func<Person, string> nameProjection = p => p.Name;is equivalent to:
Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };In both cases you're creating a delegate with a Person parameter, returning that person's name (as a string).
In C# 6 the same syntax is used for expression-bodied members, e.g.
// Expression-bodied property public int IsValid => name != null && id != -1; // Expression-bodied method public int GetHashCode() => id.GetHashCode();See also:
- What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)
- What is a Lambda?
- C# Lambda expression, why should I use this?
(And indeed many similar questions - try the lambda and lambda-expressions tags.)
更多推荐
'=>' 是什么意思C#中的语法是什么意思?
发布评论