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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/290061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:51:09  来源:igfitidea点击:

What does the '=>' syntax in C# mean?

c#syntax

提问by Wolf5

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?

那么谁能告诉我它是什么以及它是如何使用的?

采纳答案by Jon Skeet

It's the lambda operator.

它是 lambda 运算符。

From C# 3 to C# 5, this was only used for lambda expressions. These are basically a shorter form of the anonymous methodsintroduced in C# 2, but can also be converted into expression trees.

从 C# 3 到 C# 5,这仅用于lambda 表达式。这些基本上是C# 2 中引入的匿名方法的较短形式,但也可以转换为表达式树

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 Personparameter, returning that person's name (as a string).

在这两种情况下,您都使用Person参数创建委托,返回该人的姓名(作为字符串)。

In C# 6 the same syntax is used for expression-bodied members, e.g.

在 C# 6 中,相同的语法用于表达式主体成员,例如

// 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 lambdaand lambda-expressionstags.)

(实际上还有许多类似的问题 - 试试lambdalambda-expressions标签。)

回答by milot

Instead of using anonymous method like this:

而不是使用这样的匿名方法:

somevar.Find(delegate(int n)
{
   if(n < 10)
      return n;
});

you simply write it like this:

你只需像这样写:

somevar.Find(n => n < 10);

It will take the data type based on the return value.

它将根据返回值采用数据类型。

回答by qui

It basically means "goes into", like a parameter

它基本上意味着“进入”,就像一个参数

MyObjectReference => MyObjectReference.DoSomething()

Usually you use them to pass functions into methods as parameters, or in LINQ statements

通常你使用它们将函数作为参数传递给方法,或者在 LINQ 语句中

MyCollection.Where(myobj => myobj.Age>10)

For example.

例如。

回答by Serhat Ozgel

It means awesomeness. For e.g.

这意味着了不起。例如

x => x + 1

represents a method which takes x as a parameter and returns the successor of it.

表示一个将 x 作为参数并返回它的后继的方法。

button.Click += new EventHandler((sender, e) => methodInfo.Invoke(null, new object[] { sender, e }));

assigns an event handler to a button by invoking a method that a MethodInfo holds.

通过调用 MethodInfo 持有的方法将事件处理程序分配给按钮。

回答by Steve

here's a simple example from msdn

这是来自 msdn 的一个简单示例

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

Anything before the => are the input parameters, and anything after is the expression. You can have multiple input parameters. Lambdas are mainly used with Linq.

=> 之前的任何内容都是输入参数,之后的任何内容都是表达式。您可以有多个输入参数。Lambda 主要用于 Linq。

回答by JonStonecash

It is part of the syntax of a lambda expression. A lambda expression is essentially a shortened form of a delegate or of an anonymous method. To illustrate, assume that I have an array of strings matching the letters of the alphabet. I could pick out the members of that array that contained values greater than "E" with the following LINQ expression:

它是 lambda 表达式语法的一部分。lambda 表达式本质上是委托或匿名方法的缩写形式。为了说明,假设我有一个与字母表字母匹配的字符串数组。我可以使用以下 LINQ 表达式挑选出包含大于“E”的值的数组成员:

var someLetters = alphabet.Where(l => l > "E");

var someLetters =alphabet.Where(l => l > "E");

The part of the lambda expression to the left of the "=>" identifies the variable name for the test (which is set to the individual members of alphabet) and the part of the lambda expression to the right of the "=>" identifies the processing. In this case the processing produces a boolean value that the Where logic uses to determine if each member of the alphabet is passed through to the someLetters array.

“=>”左侧的 lambda 表达式部分标识测试的变量名称(设置为字母表的各个成员),“=>”右侧的 lambda 表达式部分标识处理。在这种情况下,处理会生成一个布尔值,Where 逻辑使用该值来确定字母表的每个成员是否都传递到 someLetters 数组。

回答by Dave Cousineau

It is another form of function notation. The following are roughly equivalent:

它是另一种形式的函数符号。以下是大致等效的:

// explicit function
int MyFunc(int pParam)
{
   return pParam;
}

// delegate function
Func<int, int> MyFunc = delegate(int pParam) { return pParam; };

// lambda expression
Func<int, int> MyFunc = x => x;

Think of a lambda expression as saying, "given something, return something". In the example above, the function x => xsays "given x, return x". (Although lambda expressions do not necessarily need to return something, in which case you might read them as "given x, do something with x".)

把 lambda 表达式想象成说,“给定一些东西,返回一些东西”。在上面的例子中,函数x => x说“给定 x,返回 x”。(尽管 lambda 表达式不一定需要返回某些内容,在这种情况下,您可以将它们读作“给定 x,用 x 做某事”。)

回答by Sharon AS

The =>token is supported in two forms: as the lambda operatorand as a separatorof a member name and the member implementation in an expression body definition.

=>令牌支持两种形式:作为拉姆达操作者和作为一个分离器的成员名和在表达式主体定义的成员实现。

Lambda operator

Lambda 运算符

In lambda expressions, the lambda operator => separates the input variables on the left side from the lambda body on the right side.

在 lambda 表达式中,lambda 运算符 => 将左侧的输入变量与右侧的 lambda 主体分开。

The following example uses the LINQ feature with method syntax to demonstrate the usage of lambda expressions:

以下示例使用 LINQ 功能和方法语法来演示 lambda 表达式的用法:

string[] words = { "bot", "apple", "apricot" };
int minimalLength = words
  .Where(w => w.StartsWith("a"))
  .Min(w => w.Length);
Console.WriteLine(minimalLength);   // output: 5

Expression body definition

表达式体定义

An expression body definition has the following general syntax:

表达式主体定义具有以下通用语法:

member => expression;

where expression is a valid expression. Note that expression can be a statement expression only if the member's return type is void, or if the member is a constructor, a finalizer, or a property set accessor.

其中表达式是一个有效的表达式。请注意,仅当成员的返回类型为 void,或者成员是构造函数、终结器或属性集访问器时,表达式才可以是语句表达式。

The following example shows an expression body definition for a Person.ToString method:

以下示例显示了 Person.ToString 方法的表达式主体定义:

public override string ToString() => $"{fname} {lname}".Trim();

It's a shorthand version of the following method definition:

它是以下方法定义的简写版本:

public override string ToString()
{
   return $"{fname} {lname}".Trim();
}