簡體   English   中英

為什么集合初始值設定項不與表達式body屬性一起使用?

[英]Why collection initializer is not working together with expression body property?

我認為現在最好顯示代碼:

class Foo
{
    public ICollection<int> Ints1 { get; } = new List<int>();

    public ICollection<int> Ints2 => new List<int>();
}

class Program
{
    private static void Main(string[] args)
    {
        var foo = new Foo
        {
            Ints1 = { 1, 2, 3 },
            Ints2 = { 4, 5, 6 }
        };

        foreach (var i in foo.Ints1)
            Console.WriteLine(i);

        foreach (var i in foo.Ints2)
            Console.WriteLine(i);
    }
}

顯然, Main方法應該打印1,2,3,4,5,6,但它只打印1,2,3。 初始化后foo.Ints2.Count等於零。 為什么?

這是因為您已經定義了Int2屬性。 雖然它確實是一個吸氣劑,但它總是會返回一個新列表。 Int1是一個只讀的自動屬性,所以它總是返回相同的列表。 下面為類Foo刪除了等效的編譯器魔術代碼:

class Foo
{
    private readonly ICollection<int> ints1 = new List<int>(); 
    public ICollection<int> Ints1 { get { return this.ints1; } }

    public ICollection<int> Ints2 { get { return new List<int>(); } }
}

正如您所看到的,Ints2的所有變異都會丟失,因為列表總是新的。

Ints2 => new List<int>(); Ints2 { get { return new List<int>(); } } Ints2 { get { return new List<int>(); } } 每次讀取屬性時,它都會返回一個新的空列表。 您已經有了修復:您的第一個表單將列表存儲在一個字段中。

每次訪問Ints2屬性時,它都會返回新的List<int>實例。

public ICollection<int> Ints1 { get; } = new List<int>();

此行表示使用new List<int>()初始化屬性返回的支持字段。

什么集合初始化要做的就是調用Add每個元素的方法,所以Ints1將有3個元素( 123 )。


public ICollection<int> Ints2 => new List<int>();

表達身體意味着你正在定義getter的主體,如下所示:

public ICollection<int> Ints2 => new List<int>();
{
    get 
    {
        return new List<int>();
    }
}

每次調用Ints2都會返回一個新實例,這就是Count屬性返回0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM