[英]What does '=>' mean (in functions / property context)?
在开发 Xamarin 应用程序时,我使用 Lambdas 获得了自动生成的代码:
public override string this[int position] => throw new NotImplementedException();
public override int Count => throw new NotImplementedException();
=>
运算符在这种情况下是什么意思?
感谢 R
这些不是 lambda,它们是Expression-bodied Members !
在属性的上下文中,这些基本上是简化为单个表达式(而不是整个语句)的属性的 getter。
这个:
public override int Count => throw new NotImplementedException();
相当于:
public override int Count {
get { throw new NotImplementedException(); }
}
正如@sweeper 在您的示例中所说,它们与 lambda 表达式无关,因为它们是表达式主体运算符(在 C# 6 中引入并在 7 中扩展)。 不过,它也用于表示 lambda 表达式,因此它的用法有两种。
有关=>
运算符的每种用法的更多信息,请参见此处; https://learn.microsoft.com/en-us/do.net/csharp/language-reference/operators/lambda-operator
首先,让我们澄清一下=>
运算符目前在两种不同的上下文中使用:
Lambda 个表达式。 通常您会在 Linq 中看到它们,例如var query = Customers.OrderBy(x => x.CompanyName);
表达式体函数。 这就是我们这里所拥有的。
为了理解=>
的含义,请看下面的简单示例:
using System;
public class Program
{
public void Main()
{
var obj = new Test();
obj.Count.Dump();
obj[7].Dump();
}
class Test
{
public int Count => 1;
public string this[int position] => $"2 x {position} = {(2*position)}";
}
}
倾倒对象(Int32)
1个
转储对象(字符串)
2×7 = 14
在这里, NotImplementedException
代码,它只是告诉你(开发人员)属性和索引器没有实现但应该被实现,被一些 function 取代:
[... ]
应用于 object 时,都会返回双倍索引请注意,在 C# 的早期版本中,您必须编写:
class Test
{
public int Count { get { return 1; } }
public string this[int position] {
get { return String.Format("2 x {0} = {1}",
position, (2*position).ToString()); }}
}
这相当于上面的代码。 所以本质上,在 C#7 中,您必须输入更少的代码才能获得相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.