2012-05-17 31 views
1

中的代碼行問題與List.Add():它僅保存最後添加的項目

tempList.Add(orderables); 

在這個全碼:

AssociatedComboItems ai = new AssociatedComboItems(); 
    List<Orderables> tempList = new List<Orderables>(); 
    Orderables orderables = new Orderables(); 

    foreach (var t in comboBox1.Items) 
    { 
     ai.ComboBoxItem = t.ToString(); 

     for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++) 
     { 
      orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text; 
      orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value; 
      orderables.DisplayOrder = i; 
      tempList.Add(orderables); 
     } 

     ai.AssociatedItems = tempList; 
     tempList.Clear(); 
     if(AssociatedItems == null) 
     AssociatedItems = new List<AssociatedComboItems>(); 
     AssociatedItems.Add(ai); 
    } 

,當我把我的斷點上線如上所述(tempList.Add(orderables);) 它第一次正確地將項目添加到templist,它將有一個項目在其中。第二次它將正確的項目列表,但如果我將鼠標懸停在tempList上,並希望查看其內容,雖然它有兩個項目,但他們都是相同的,他們現在都是第二個項目被添加到所以它已經覆蓋了第一個,...

我不明白這是什麼問題,爲什麼發生。

謝謝大家。

+1

tempList.Clear();清空列表 –

回答

7

您需要實例化 內的 for循環;否則,你在所有的迭代中都重複使用相同的實例(並且每次都覆蓋它的屬性)。

AssociatedComboItems ai = new AssociatedComboItems(); 
List<Orderables> tempList = new List<Orderables>(); 

foreach (var t in comboBox1.Items) 
{ 
    ai.ComboBoxItem = t.ToString(); 

    for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++) 
    { 
     Orderables orderables = new Orderables(); // ← Instantiate here 
     orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text; 
     orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value; 
     orderables.DisplayOrder = i; 
     tempList.Add(orderables); 
    } 

    ai.AssociatedItems = tempList; 
    tempList.Clear(); 
    if(AssociatedItems == null) 
    AssociatedItems = new List<AssociatedComboItems>(); 
    AssociatedItems.Add(ai); 
} 

無關的問題:您可能會發現object initializer語法更清潔:

 Orderables orderables = new Orderables 
     { 
      Display = fpSpread1.ActiveSheet.Cells[i, 1].Text, 
      ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value, 
      DisplayOrder = i, 
     }; 
+0

謝謝。這解決了它。對於我的學習目的:我認爲一個對象就足夠了,因爲每次我爲它分配新值並將它傳遞給列表時......因爲它是一個引用類型?這就是原因? – Bohn

+1

準確。引用類型(類)與值類型(結構)不同,因爲後者在賦值時被複制(例如,當傳遞給「列表.Add」方法),而前者僅複製_reference_(指針),但仍指向同一個對象(實例)。因此,通過引用它的任何變量來改變對象的狀態也會「出現」在所有其他變量上。 – Douglas

+1

非常感謝。 – Bohn

1

問題是,您只有一個可配置實例,並且您不斷更改同一個實例並將其重新添加到列表中。列表中的每個引用都指向同一個對象。將可訂購產品聲明放在內部for循環中,它將解決問題。

相關問題