这是什么语法

时间:2015-10-13 13:23:18

标签: c#

我在NodaTime中看到了这段代码。这是这里的代码

public bool Equals(DateInterval other) => this == other;

此代码使用=>运算符来定义函数体。我尝试使用语法创建一个项目,但一直给我一个错误。我正在使用visual studio 2012.如何在我的代码中使用相同的语法。

3 个答案:

答案 0 :(得分:6)

这是C#6中的表达式功能。它在Visual Studio 2015及更高版本中受支持。您可以在announcement of C# 6上阅读更多内容(查找“Expression Bodied Functions and Properties”)。

答案 1 :(得分:2)

public bool Equals(DateInterval other) => this == other;

相当于:

public bool Equals(DateInterval other)
{
   return this==other;
}

答案 2 :(得分:1)

Expression-bodied函数成员允许属性,方法,运算符和其他函数成员将主体作为lambda类表达式而不是语句块。从而减少代码行和清晰的表达视图。

现在在C#6.0中,您现在可以使用lambda箭头(“=>”)返回值,而不是使用getter / setter编写整个属性体。

例如,当您访问属性“NewName”时,以下代码返回字符串“My Name”。请记住,在这种情况下,您不必编写“return”关键字。 lambda箭头(=>)将在内部为您做同样的事情。

Public string NewName=>"My Name" //this is the new way 
public string NewName//this was the old 
{
  get
  {
    return "My Name";
  }
}

另一个例子

Public int NewSum(int a,int b)=>a+b;//new way

public int oldSum(int a,int b)//old way
{
  return a+b;
}

Link Here