'=>' 是什么意思C#中的语法是什么意思?

编程入门 行业动态 更新时间:2024-10-11 09:28:49
本文介绍了'=>' 是什么意思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();

另见:

  • 有什么区别匿名方法 (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#中的语法是什么意思?

本文发布于:2023-06-03 09:48:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/471173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!