List.Add()的问题仅保存最后添加的项目

我注意到的问题是这行代码:

tempList.Add(orderables); 

在这个完整的代码中:

 AssociatedComboItems ai = new AssociatedComboItems(); List tempList = new List(); 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(); AssociatedItems.Add(ai); } 

当我将断点放在上面提到的那一行( tempList.Add(orderables); )时,第一次将项正确地添加到templist ,它将有一个项目。 第二次它会将正确的项添加到列表中, 如果我将鼠标hover在tempList并希望查看其内容,虽然它有两个项目,但它们都是相同的 – 它们现在都是添加到第二个项目中的第二个项目名单。 它覆盖了第一个。

我无法弄清楚这有什么问题以及为什么会发生这种情况。

您需要 for循环中实例化Orderables ; 否则,您将继续在所有迭代中重用相同的实例(并且每次都覆盖其属性)。

 AssociatedComboItems ai = new AssociatedComboItems(); List tempList = new List(); 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(); AssociatedItems.Add(ai); } 

与问题无关:您可能会发现对象初始化程序语法更清晰:

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

问题是您只有一个orderables实例,并且您不断更改同一个实例并将其重新添加到列表中。 列表中的每个引用都指向同一个对象。 在内部for循环中移动orderables声明,它将解决问题。