C#6中(自动)属性初始化语法之间的差异

C#6中(自动)属性初始化语法之间的差异,c#,properties,c#-6.0,C#,Properties,C# 6.0,以下用于初始化C#6中属性的表达式之间有什么区别: 1。从构造函数初始化的自动属性 public class Context1 { public Context1() { this.Items = new List<string>(); } public List<string> Items { get; private set; } } 公共类上下文1 { 公共上下文1() { this.Items=新列表(); }

以下用于初始化C#6中属性的表达式之间有什么区别:

1。从构造函数初始化的自动属性

public class Context1
{
    public Context1()
    {
        this.Items = new List<string>();
    }

    public List<string> Items { get; private set; }
}
公共类上下文1
{
公共上下文1()
{
this.Items=新列表();
}
公共列表项{get;private set;}
}
2:从支持字段初始化的属性

public class Context2
{
    private readonly List<string> items;

    public Context2()
    {
        this.items = new List<string>();
    }

    public List<string> Items
    {
        get
        {
            return this.items;
        }
    }
}
公共类上下文2
{
私有只读列表项;
公共上下文2()
{
this.items=新列表();
}
公共清单项目
{
得到
{
归还此物品;
}
}
}
3:C#6中的自动属性新语法

public class Context3
{
    public List<string> Items { get; } = new List<string>();
}
public class Context4
{
    public List<string> Items => new List<string>();
}
公共类上下文3
{
公共列表项{get;}=new List();
}
4:C#6中的自动属性新语法

public class Context3
{
    public List<string> Items { get; } = new List<string>();
}
public class Context4
{
    public List<string> Items => new List<string>();
}
公共类上下文4
{
公共列表项=>新列表();
}
清单3是C#6与清单2的等价物,其中支持字段在引擎盖下提供

清单4:

public List<string> Items => new List<string>();
public List Items=>newlist();
相当于:

public List<string> Items { get { return new List<string>(); } }
公共列表项{get{return new List();}
可以想象,每次访问属性时,它都会返回一个新的空列表

清单2/3和清单4之间的差异将通过一个示例进一步探讨


清单1只是一个带有getter和private setter的auto属性。它不是只读属性,因为您可以在任何可以访问该类型的任何私有成员的地方设置它。只读属性(即仅getter属性)只能在构造函数或属性声明中初始化,这与只读字段非常相似。

自动属性是自动实现属性的简称,开发人员不需要显式声明备份字段,编译器在后台设置备份字段

1.具有私有setter的自动属性 这些具有不同可访问性的访问器可以在可访问性确定的任何位置访问,而不仅仅是从构造函数访问

2.带支持字段的只读属性 公共类上下文2 { 私有只读列表项

public Context2()
{
    this.items = new List<string>();
}

public List<string> Items
{
    get { return this.items; }
}
C#6开始,编译器可以通过生成一个类似于读写自动属性的支持字段来处理§2,但在这种情况下,支持字段是只读的,只能在对象构造期间设置

4.具有表达式bodied getter的只读自动属性
公共类上下文4
{
公共列表项=>新列表();
}
当属性的值在每次获取时都会更改时,C#6允许使用类似lambda的语法声明getter的主体

上述代码与此等效:

public class Context4
{
    public List<string> Items
    {
        get { return new List<string>(); }
    }
}
公共类上下文4
{
公共清单项目
{
获取{返回新列表();}
}
}

所以数字4就像一个常量,但有一个引用类型!?如果“常量”的意思是“不断地返回这个值的一个新实例”(a la),那么……嗯,我想是的。但这不是“常量”的意思。引用类型不能是常量是有原因的。数字1和2相似吗?
public class Context4
{
    public List<string> Items => new List<string>();
}
public class Context4
{
    public List<string> Items
    {
        get { return new List<string>(); }
    }
}