c# 6中(auto)属性初始化语法的区别

本文关键字:初始化 语法 区别 属性 auto | 更新日期: 2023-09-27 18:18:34

c# 6中初始化属性的表达式有什么不同?

1。从构造函数

初始化Auto-Property
public class Context1
{
    public Context1()
    {
        this.Items = new List<string>();
    }
    public List<string> 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;
        }
    }
}

3: c# 6中的Auto-Property新语法

public class Context3
{
    public List<string> Items { get; } = new List<string>();
}

4: c# 6中的Auto-Property新语法

public class Context4
{
    public List<string> Items => new List<string>();
}

c# 6中(auto)属性初始化语法的区别

清单3是c# 6中与清单2等价的部分,其中的后台字段是在底层提供的。

清单4:

public List<string> Items => new List<string>();

等价于:

public List<string> Items { get { return new List<string>(); } }

,你可以想象每次你访问属性返回一个新的空列表。

清单2/3和清单4之间的区别将在本问答中通过一个示例进一步探讨。

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

Auto-property自动实现属性的简称,开发人员不需要显式声明支持字段,编译器在后台设置一个。

<标题> 1。带有私有setter的Auto-Property
public class Context1
{
    public Context1()
    {
        this.Items = new List<string>();
    }
    public List<string> Items { get; private set; }
}

通过为不同于属性的访问器指定更严格的可访问性,自动属性可以对setter和getter具有不同的可访问性。

public string Prop1 { get; private set; }
public string Prop2 { get; protected set; }
public string Prop3 { get; internal set; }
public string Prop4 { protected internal get; set; }

这些具有不同可访问性的访问器可以在可访问性决定的任何地方访问,而不仅仅是从构造函数访问。

<标题> 2。带支持字段的只读属性

公共类Context2{private readonly列表项;

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

}在 c# 6之前,设置只读属性值的唯一方法是显式声明支持字段并直接设置。

由于该字段具有readonly访问器,因此只能在对象构造期间设置。

<标题> 3。只读Auto-Property h1> c# 6开始,§2可以由编译器通过生成一个支持字段来处理,就像读写自动属性一样,但是在这种情况下,支持字段是只读的,只能在对象构造期间设置。 <标题> 4。带有表达式体getter的只读Auto-Property
public class Context4
{
    public List<string> Items => new List<string>();
}

当属性的值在每次获取时都改变时,c# 6允许使用类似于lambda的语法声明getter的主体。

上面的代码相当于:

public class Context4
{
    public List<string> Items
    {
        get { return new List<string>(); }
    }
}