Open1
【C#】ReadOnlyCollectionについて
参考になる記事
IReadOnlyList<T>, ReadOnlyCollection<T>, ImmutableList<T>の違いを一言で
・IReadOnlyList<T>: インターフェースだが、実態はあくまで具象クラスを参照しているため、キャストすれば参照先のList<T>を変更可能。
・ReadOnlyCollection<T>: 元となるList<T>の「参照」がラップされるので、List<T>は変更されない。
・ImmutableList<T>: ReadOnlyCollection<T>と違い、参照ではなくList<T>の「コピー」をラップする。
ReadOnlyCollection<T>は、参照元のList<T>の要素が変更が反映される。
ImmutableList<T>は参照元のList<T>の要素の変更が反映されない。
ReadOnlyCollection<T>は、参照元のList<T>がnewなどでList<T>の参照先が変更されても、newされる前のList<T>を参照し続ける。
List<int> intList = new List<int>();
intList.Add(3);
ReadOnlyCollection<int> read = intList.AsReadOnly(); // read == {3}
intList.Add(5); // read == {3, 5}
intList = new List<int>();
intList.Add(2); // read == {3, 5}
ReadOnlyCollection<int> read2 = intList.AsReadOnly(); // read == {3, 5}, read2 == {2}