【问题标题】:What is the way to write the new get and set properties in C# 6.0 when has more sentences?当有更多句子时,在 C# 6.0 中编写新的 get 和 set 属性的方法是什么?
【发布时间】:2018-08-20 16:54:30
【问题描述】:

在上个C#版本的属性get和set中,多语句的写法是:

ObservableCollection<Product> products;
public ObservableCollection<Product> Products
{
   get
   {
     return products;
   }
   set
   {
     products = value;
     OnPropertyChanged("Products");
   }
}

但是在 C# 6.0 中是怎样的呢?因为新样式是使用 lambda 运算符:

ObservableCollection<Product> products;
public ObservableCollection<Product> Products
{ 
  get => products; 
  set => products= value; 
}

谢谢。

【问题讨论】:

    标签: c#-6.0


    【解决方案1】:

    Auto-Implemented Properties(自动属性)从 c# 3 开始就存在了。

    public int Age { get; set; }
    

    C# 6 做了一些改进,其中之一是 Auto-Property Initializers

    public int Age { get; } = 30;
    

    但我认为您要使用的是另一个功能,表达式主体函数成员

    public void SayHello(string name) => Console.WriteLine("hello {0}", name);
    
    public string FullName => string.Format("{0} {1}", FirstName, LastName);
    

    表达式体函数成员
    我们编写的许多成员的主体由只有一个语句组成,可以表示为表达式。您可以通过编写表达式主体成员来减少该语法。它适用于方法和只读属性

    Expression-bodied function members

    你不能在你的情况下使用它们,因为你的属性不是只读的。

    也许这可以帮助你。
    How to implement INotifyPropertyChanged in C# 6.0?

    更新:

    C# 7 引入了您想要的语法,但仅适用于单行表达式。

    属性集声明(link)
    如果您选择自己实现属性集访问器,则可以为 单行表达式 使用表达式主体定义,将值分配给支持属性的字段。

    public class Location
    {
       private string locationName;
    
       public Location(string name) => Name = name;
    
       public string Name
       {
          get => locationName;
          set => locationName = value;
       } 
    }
    

    【讨论】:

    • 谢谢,所以我必须使用旧样式:set { products = value; OnPropertyChanged("产品"); }
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多