c# - 转换为表达式主体似乎不起作用?

标签 c# lambda

我有以下代码:

public bool IsUser
{
    get { return false; }
}

现在 Resharper 建议我将它写到:

public bool UseBands => false;

然而这并没有编译,我的编译器提示我应该添加一个“;”?

更新

我在 Visual Studio 2013 Update 4 上使用 Resharper 9 时遇到过这个问题。Resharper 似乎在查看项目属性,它应该应用哪些建议规则。如果您遇到此问题,那么可能如 Szer 所述,您已经启用了 C# 6.0 语言级别。

要禁用它,只需在解决方案资源管理器中单击您的项目,然后将 C# 语言级别设置为 C# 6.0 以外的级别。

PS:由于我对更改项目设置的了解有限,我不知道有设置此功能的功能。尽管我不记得更改过它(C# 语言级别)。感谢您的所有帮助。

最佳答案

根据 MSDN,这是 C#6 的功能之一。 ReSharper9 部分支持它,您可能提前启用了它。

引自 MSDN:

Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.

Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:

public Point Move(int dx, int dy) => new Point(x + dx, y + dy); 
public static Complex operator +(Complex a, Complex b) => a.Add(b); 
public static implicit operator string(Person p) => "\{p.First} \{p.Last}";

The effect is exactly the same as if the methods had had a block body with a single return statement.

For void returning methods – and Task returning async methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression (just as is the rule for lambdas):

public void Print() => Console.WriteLine(First + " " + Last);

Properties and indexers can have getters and settersgetter-only properties and indexers can have an expression body:

public string Name => First + " " + Last; 
public Customer this[long id] => store.LookupCustomer(id);

Note that there is no get keyword: it is implied by the use of the expression body syntax.

更多信息:http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx

关于c# - 转换为表达式主体似乎不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28340876/

相关文章:

c# - 如何使用 Selenium WebDriver 和 c# 从 Telerik RadComboBox 中选择一个选项?

c# - 如何在 Visual Studio 中确定当前插入符号位置位于注释 block 中?

c# - 跨线程调用编译问题

lambda - 修复 lambda 表达式的 uncrustify 格式

C# - 在 LINQ sum 方法中计算值时应该无法访问代码

lambda - 如何使用 Google Blogger Lambda 运算符

c# - 跨页面传递值 ASP.net

c# - SingleLine 选项和\n 字符串结尾之前的正则表达式问题

c# - VS 2015 中未显示停止调试器按钮

asp.net-mvc-3 - ASP.NET MVC 强类型 HTML 帮助程序