'=>' 是什么意思C#中的语法是什么意思? [英] What does the '=>' syntax in C# mean?

查看:59
本文介绍了'=>' 是什么意思C#中的语法是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在本论坛的一些问题中遇到了这种语法,但 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();

另见:

(确实有许多类似的问题 - 试试 lambdalambda-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:

(And indeed many similar questions - try the lambda and lambda-expressions tags.)

这篇关于'=>' 是什么意思C#中的语法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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