2012-10-24 22 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