2012-10-24 36 views
1
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 

问题是初始化框阵列的第一 元件之后改变。 boxesList也被改变。 我认为问题在于 数组在列表中存储为引用。 有没有办法解决这个问题? 从而使boxeslist不会通过改变框阵列C#防止作出列出

+0

所以你想要在列表中存储数组的克隆,而不是原始数组?这是你的问题吗? –

回答

7

被改变的问题是初始化框阵列的第一个元素之后。 boxesList也被改变。

不,不是这样的。该boxesList具有正好相同的内容,因为它有:参考框的数组。这里只有一个数组。如果你改变它,无论是通过boxesList[0]boxes,你正在改变相同的数组。

如果你想获取数组的副本,你需要明确地这样做。无论您是创建数组的副本还是将引用放入列表中,还是复制数组,都由您决定。

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

+0

谢谢,我想我会制作一个数组的副本并将其放入列表中 – snorifu

3

数组是参考。将数组放入列表中时,它只是复制参考。如果你想要一个新的单独阵列(相同的实际物体的),那么你就需要到阵列复制:

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

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

boxes[0].SomeProp = newValue; 

仍然会显示在这两个地方。如果这不行,那么深层复制可能是有用的,但坦率地说,我建议这样做会更容易使Box不可变。

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