且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VS2017 带有新的 getter/setter 语法:如何在 setter 中编写多行?/

更新时间:2023-12-04 13:57:52

好的,让我们再看一遍.你想写

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:

  1. 不返回任何东西(抛出异常就是异常,双关语)
  2. 由多个表达式组成.
  3. 是否是因为它产生的副作用.

当然第 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.