C#阻止对列表进行更改

时间:2012-10-24 12:42:26

标签: c# arrays list

List<Box[]> boxesList = new List<Box[]>(); // create a new list that contains boxes
Box[] boxes = new Box[9];                  // create an array of boxes
boxesList.Add(boxes);                      // add the boxes to the list
boxesList[0][0] = new Box(2, new Point(0, 0)); // change the content of the list
boxes[0] = new Box(1,new Point(0,0));      //  change content of the boxarray

问题出在初始化第一个之后 box数组的元素。 boxesList也被更改。 我认为问题在于盒子 数组存储为列表中的引用。 有没有解决的办法? 因此,不会通过更改框数组来更改框列表

3 个答案:

答案 0 :(得分:7)

  

问题是在初始化box数组的第一个元素之后。 boxesList也被更改。

不,不是。 boxesList 完全的内容相同:引用到框数组。这里只有一个数组。如果您更改它,无论是通过boxesList[0]还是boxes,您都会更改相同的数组。

如果要获取数组的副本,则需要明确地执行此操作。是否创建数组的副本并将引用放在列表中的副本,或者之后复制数组取决于您。

有关更多信息,请参阅我在reference types and value types上的文章,记住所有数组类型都是引用类型。

答案 1 :(得分:3)

数组是引用。将数组放入列表时,只是复制引用。如果你想要一个新的单独的数组(相同的实际对象),那么你需要复制数组:

boxedList.Add((Box[])boxes.Clone());

请注意,这只是一个浅拷贝;这一行:

boxes[0].SomeProp = newValue;

仍将在两个地方展示。如果不行,那么深层拷贝可能会有用,但坦率地说,我建议让Box变得更加容易。

答案 2 :(得分:0)

您正在覆盖列表中第一个元素的索引。将代码更改为此选项,两个框都显示在列表中。

        List<Box[]> boxesList = new List<Box[]>(); // create a new list that contains boxes
        Box[] boxes = new Box[9];                  // create an array of boxes
        boxesList.Add(new Box[] { new Box(2, new Point(0, 0))}); // change the content of the list
        boxes[0] = new Box(1, new Point(0, 0)); 
        boxesList.Add(boxes);                      // add the boxes to the list