VS2017 新的 getter/setter 语法:如何在 setter 中写多行?/ [英] VS2017 with new getter/setter syntax: How to write multiple lines in the setter?/

查看:20
本文介绍了VS2017 新的 getter/setter 语法:如何在 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"); }
}

对于上述设置器,我得到 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:

  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.

这篇关于VS2017 新的 getter/setter 语法:如何在 setter 中写多行?/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆