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

Boh*_*ohn 3 c#

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

tempList.Add(orderables);
Run Code Online (Sandbox Code Playgroud)

在这个完整的代码中:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

我无法弄清楚这有什么问题,为什么会发生这种情况.

Dou*_*las 8

你需要Orderables 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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