J. *_*Doe 5 c# lambda function
我在下面的例子中看到了一个运算符 =>:
public int Calculate(int x) => DoSomething(x);
Run Code Online (Sandbox Code Playgroud)
或者
public void DoSoething() => SomeOtherMethod();
Run Code Online (Sandbox Code Playgroud)
除了在 Lamba 表达式中,我以前从未见过像这样使用这个运算符。
以下有什么作用?应该在哪里、什么时候使用?
这些是 C# 6 中引入的 Expression Body 语句。重点是使用类似 lambda 的语法来单行简单的属性和方法。上述陈述由此展开;
public int Calculate(int x)
{
return DoSomething(x);
}
public void DoSoething()
{
SomeOtherMethod();
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,属性也接受表达式主体以创建简单的仅获取属性:
public int Random => 5;
Run Code Online (Sandbox Code Playgroud)
相当于
public int Random
{
get
{
return 5;
}
}
Run Code Online (Sandbox Code Playgroud)
看看这篇微软文章。这是C# 6.0属性没有声明主体的功能。您可以将它们用于get方法或单行表达式。例如:
public override string ToString() => string.Format("{0}, {1}", First, Second);
Run Code Online (Sandbox Code Playgroud)