问题描述
我使用ReadOnlyCollection还使对象不可变的努力,我想对象的属性是不可改变的。
I'm trying using ReadOnlyCollection to make object immutable, I want the property of object are immutable.
public ReadOnlyCollection<FooObject> MyReadOnlyList
{
get
{
return new ReadOnlyCollection<FooObject>(_myDataList);
}
}
不过,我有点糊涂了。
But I little confused.
我试图用一个foreach来更改对象的属性MyReadOnlyList和...我可以改变value属性,它是正确的?我明白ReadOnlyCollection还设置一个附加的水平,使对象不可改变的。
I tried to change the property of the object in to MyReadOnlyList using a foreach and ... I can change value property, is it correct? I understood ReadOnlyCollection set an add level to make the object immutable.
推荐答案
事实上, ReadOnlyCollection还
是不可变意味着集合不能被修改,即没有对象可以添加或从集合中删除。这并不意味着该对象包含不可变的。
The fact that ReadOnlyCollection
is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection. This does not mean that the objects it contains immutable.
,说明如何不同类型的不可改变的工作。基本上,一个 ReadOnlyCollection还
是一个不变的外观可以读出底层集合( _myDataList
),但不能对其进行修改。但是,您仍然可以更改底层集合,因为你必须做一些像 _myDataList [0] = NULL $ C $到
_myDataList
参考C>。
This article by Eric Lippert, explains how different kinds of immutability work. Basically, a ReadOnlyCollection
is an immutable facade which can read the underlying collection (_myDataList
), but cannot modify it. However, you can still change the underlying collection since you have a reference to _myDataList
by doing something like _myDataList[0] = null
.
此外,>按 ReadOnlyCollection还
_myDataList ,即 this._myDataList.First()== this.MyReadOnlyList.First()
(用 LINQ
)。这意味着,如果一个对象 _myDataList
是可变的,那么在对象 MyReadOnlyList
。
Furthermore, the objects returned by ReadOnlyCollection
are the same ones returned by _myDataList
, i.e. this._myDataList.First() == this.MyReadOnlyList.First()
(with LINQ
). This means that if an object in _myDataList
is mutable, then so is the object in MyReadOnlyList
.
如果您希望对象是不变的,则应该相应地设计他们。例如,你可以使用:
If you want the objects to be immutable, you should design them accordingly. For instance, you might use:
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; }
}
而不是:
instead of:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
编辑:在这种情况下,由,无论是结构允许你修改集合中的元素属性。这是因为结构是值类型,当你访问一个元素集合返回值的副本。只能修改的属性点
,如果它是一类,这将意味着实际对象的引用返回,而不是它们的值的副本类型。
in this case, as noted by Ian Goldby, neither struct allows you to modify properties of the elements in the collection. This happens because structs are value types and when you access an element the collection returns a copy of the value. You can only modify the properties of a Point
type if it is a class, which would mean that references to the actual objects are returned, instead of copies of their values.
这篇关于ReadOnlyCollection还,是对象不可改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!