2016-04-27 31 views
3

我認爲這是最好的,現在顯示的代碼:爲什麼集合初始值設定項與表達式主體屬性不能一起工作?

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等於零。爲什麼?

+3

您的'Ints2'在每次訪問時創建新的'List'。 – PetSerAl

+0

@PetSerAl,我高興,謝謝。 –

回答

5

這是因爲你如何定義屬性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>(); } } 
} 

正如你所看到的,mututations到INTS2丟失,因爲列表總是新的。

2

Ints2 => new List<int>();Ints2 { get { return new List<int>(); } }的簡稱。每次讀取屬性時它都會返回一個新的空列表。您已經有了解決方法:您的第一種形式將列表存儲在一個字段中。

2

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

1
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

相關問題