不可变的事实ReadOnlyCollection
意味着不能修改集合,即不能从集合中添加或删除任何对象。这并不意味着它包含的对象是不可变的。
Eric Lippert 的这篇文章解释了不同类型的不变性是如何工作的。基本上,aReadOnlyCollection
是一个不可变的外观,它可以读取底层集合 ( _myDataList
),但不能修改它。但是,您仍然可以更改基础集合,因为您可以_myDataList
通过执行类似_myDataList[0] = null
.
此外,返回的对象与返回的对象ReadOnlyCollection
相同_myDataList
,即this._myDataList.First() == this.MyReadOnlyList.First()
(与LINQ
)。这意味着如果 in 中的对象_myDataList
是可变的,那么 in 中的对象也是可变的MyReadOnlyList
。
如果您希望对象是不可变的,则应相应地设计它们。例如,您可以使用:
public struct Point
{
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
// In C#6, the "private set;" can be removed
public int X { get; private set; }
public int Y { get; private set; }
}
代替:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
编辑:在这种情况下,正如Ian Goldby所指出的,这两个结构都不允许您修改集合中元素的属性。发生这种情况是因为结构是值类型,并且当您访问元素时,集合会返回该值的副本。如果它是一个类,则只能修改类型的属性Point
,这意味着返回对实际对象的引用,而不是其值的副本。