Ich denke, es ist am besten jetzt den Code zu erhalten:Warum Sammlungsinitialisierer nicht mit Expression Body Eigenschaft zusammenarbeitet?
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);
}
}
Offensichtlich ist die Main
Methode 1 gedruckt werden soll, 2, 3, 4, 5, 6, aber er druckt 1, 2, 3 nur. Nach der Initialisierung ist foo.Ints2.Count
gleich Null. Warum?
Ihr 'Ints2' erstellt bei jedem Zugriff eine neue' Liste'. – PetSerAl
@PetSerAl, ich grok, danke. –