简体   繁体   English

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

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

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.它是 lambda 运算符。

From C# 3 to C# 5, this was only used for lambda expressions .从 C# 3 到 C# 5,这仅用于lambda 表达式 These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees .这些基本上是 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 Person parameter, returning that person's name (as a string).在这两种情况下,您都使用Person参数创建委托,返回该人的姓名(作为字符串)。

In C# 6 the same syntax is used for expression-bodied members , eg在 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 lambda and lambda-expressions tags.) (实际上还有许多类似的问题 - 试试lambdalambda-expressions标签。)

It's a much more concise form of method notation.这是一种更简洁的方法符号形式。 The following are roughly equivalent:以下是大致等效的:

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

// anonymous (name-less) method
// note that the method is "wrapped" up in a hidden object (Delegate) this way
// so there is a very tiny bit of overhead compared to an explicit method
// (though it's really the assignment that causes that and would also happen
// if you assigned an explicit method to a reference)
Func<int, int> MyFunc = delegate (int pParam) { return pParam; };

// lambda expression (also anonymous)
// basically identical to anonymous method,
// except with everything inferred as much as possible, intended to be minimally verbose
Func<int, int> MyFunc = x => x;

// and => is now also used for "expression-bodied" methods
// which let you omit the return keyword and braces if you can evaluate
// to something in one line
int MyFunc(int pParam) =>
   pParam;

Think of a lambda expression as saying, "given something, return something".把 lambda 表达式想象成说,“给定一些东西,返回一些东西”。 In the example above, the lambda expression x => x says "given x, return x", although lambda expressions don't 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 做某事” .

Also note that there are kind of three things called "delegate" which can be very confusing at first.另请注意,有一种称为“委托”的三样东西,起初可能会非常令人困惑。

An anonymous method uses the delegate keyword, but defines a method with no name:匿名方法使用delegate关键字,但定义了一个没有名称的方法:

Func<int, int> = delegate (int x) { return x; };

Assigning a method (anonymous, explicit, or lambda) to a reference causes a hidden Delegate wrapper object to be created that is what allows the method to be referred to.将方法(匿名、显式或 lambda)分配给引用会导致创建隐藏的Delegate包装器对象,该对象允许引用该方法。 (Basically a sort of "managed function pointer".) (基本上是一种“托管函数指针”。)

And then, you can also declare named method signatures using the delegate keyword as well:然后,您还可以使用delegate关键字声明命名方法签名

public delegate int TestFunc(int x, int y);

TestFunc myFunc = delegate (int x, int y) { return x + y; };

This declares a named signature TestFunc that takes two int s and returns an int , and then declares a delegate reference of that type which is then assigned an anonymous method with matching signature.这声明了一个命名签名TestFunc ,它接受两个int并返回一个int ,然后声明该类型的委托引用,然后为其分配一个具有匹配签名的匿名方法。

It means awesomeness.这意味着了不起。 For eg例如

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 持有的方法将事件处理程序分配给按钮。

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。

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.它将根据返回值采用数据类型。

The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition. =>标记支持两种形式:作为lambda 运算符和作为成员名称的分隔以及表达式主体定义中的成员实现。

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();
}

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.例如。

It is part of the syntax of a lambda expression.它是 lambda 表达式语法的一部分。 A lambda expression is essentially a shortened form of a delegate or of an anonymous method. lambda 表达式本质上是委托或匿名方法的缩写形式。 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:我可以使用以下 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. “=>”左侧的 lambda 表达式部分标识测试的变量名称(设置为字母表的各个成员),“=>”右侧的 lambda 表达式部分标识处理。 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.在这种情况下,处理会生成一个布尔值,Where 逻辑使用该值来确定字母表的每个成员是否都传递到 someLetters 数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM