我認爲這是最好的,現在顯示的代碼:爲什麼集合初始值設定項與表達式主體屬性不能一起工作?
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
等於零。爲什麼?
您的'Ints2'在每次訪問時創建新的'List'。 – PetSerAl
@PetSerAl,我高興,謝謝。 –