VS2017 带有新的 getter/setter 语法:如何在 setter 中编写多行?/ [英] VS2017 with new getter/setter syntax: How to write multiple lines in the setter?/
问题描述
我使用的是 .NET Framework 4.5.2,VS2017.VS2017 为 getter 和 setter 提供了新的语法.现在带有 getter setter 的属性如下所示:
I am using .NET Framework 4.5.2, VS2017. VS2017 has got new syntax for getter and setter. Now the property with getter setter looks like below:
public string Name { get => _name; set => _name = value; }
我必须编写以下属性.如何使用 lambda 表达式 set=> 编写设置器?
I have to write the below property. How can I write the setter with lambda expression set=> ?
public int EmployeeNumber
{
get => _employeeNumber;
set { _employeeNumber = value; OnPropertyChanged("EmployeeNumber");}
}
比如这样:
public int EmployeeNumber
{
get => _employeeNumber;
set =>{ _employeeNumber = value;OnPropertyChanged("EmployeeNumber"); }
}
对于上面的 setter,我得到 3 个错误:
For the above setter, I get 3 errors:
CS1525: Invalid expression term {
CS1002: ; expected
CS1014: A get or set accessor expected
推荐答案
好的,让我们再看一遍.你想写
Ok, lets go over this again. You want to write
public int EmployeeNumber
{
set
{
_employeeNumber = value;
OnPropertyChanged("EmployeeNumber");
}
}
像这样:
public int EmployeeNumber
{
set =>
{
_employeeNumber = value;
OnPropertyChanged("EmployeeNumber");
}
}
问题是为什么?表达式体函数成员的全部意义在于避免使用大括号、返回关键字等,使事情更加简洁和可读:
The question is why? The whole point about expression bodied function members is to make things more concise and readable avoiding curly braces, return keywords, etc.:
public int Foo => foo
取而代之,
public int Foo { return foo; }
您尝试做的事情并没有使其更具可读性,并添加了两个无用的额外标记.这似乎是一笔糟糕的交易.
What you are attempting to do doesn't make it more readable and adds two useless extra tokens. That seems like an awful bargain.
作为一般规则,当右侧的代码:
As a general rule, you shouldn't use (or can't use) the =>
syntax when the code on the right side:
- 不返回任何东西(抛出异常就是异常,双关语)
- 由多个表达式组成.
- 是否是因为它产生的副作用.
当然第 3 条规则是我自己的,我不知道关于这个问题的任何编码风格建议,但我倾向于避免这种语法,除非我处理没有副作用的方法.
Of course rule nº3 is mine alone, I'm not aware of any coding style recommendations on this matter but I tend to avoid this syntax unless I'm dealing with no side effects producing methods.
这篇关于VS2017 带有新的 getter/setter 语法:如何在 setter 中编写多行?/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!