私はそれが、今のコードを表示するのが最善だと思う:コレクション初期化子が式の本体プロパティと一緒に機能していないのはなぜですか?
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、私grok、ありがとう。 –