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

时间:2012-05-17 22:35:55

标签: c#

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

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上并希望查看其内容,尽管它有两个项目,它们都是相同的 - 它们现在都是添加到列表中的第二个项目。它覆盖了第一个。

我无法弄清楚这是怎么回事以及为什么会这样。

2 个答案:

答案 0 :(得分:8)

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

Orderables

与问题无关:您可能会发现object initializer语法更清晰:

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);
}

答案 1 :(得分:2)

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