C# 获得;“收藏已修改”;即使我';我正在修改另一个集合

C# 获得;“收藏已修改”;即使我';我正在修改另一个集合,c#,asp.net,collections,C#,Asp.net,Collections,好的,我知道我不允许修改当前正在遍历的集合,但看看下面的代码,您会看到我甚至没有涉及执行枚举的集合: MenuItemCollection tempItems = new MenuItemCollection(); foreach (MenuItem item in mainMenu.Items) { if (item.Value != "pen") tempItems.Add(item); } 如您所见,我向其中添加项的

好的,我知道我不允许修改当前正在遍历的集合,但看看下面的代码,您会看到我甚至没有涉及执行枚举的集合:

    MenuItemCollection tempItems = new MenuItemCollection();
    foreach (MenuItem item in mainMenu.Items)
    {
        if (item.Value != "pen")
            tempItems.Add(item);
    }
如您所见,我向其中添加项的集合与我正在迭代的集合不同。但我仍然得到了错误:

“集合已修改;枚举操作可能无法执行”

但是,如果我对代码稍作更改,并将MenuItemCollection替换为List,它会起作用:

    List<MenuItem> tempItems = new List<MenuItem>();
    foreach (MenuItem item in mainMenu.Items)
    {
        if (item.Value != "pen")
            tempItems.Add(item);
    }
List tempItems=new List();
foreach(主菜单中的菜单项。项)
{
如果(item.Value!=“笔”)
临时项目。添加(项目);
}

有人能解释一下原因吗?

当您将
MenuItem
添加到另一个
MenuItemCollection
时,它将从其所有者(即
main menu
)中删除。因此,对原始集合进行了修改:

public void Add(MenuItem child)
{
    if ((child.Owner != null) && (child.Parent == null))
         child.Owner.Items.Remove(child);

    if (child.Parent != null)    
        child.Parent.ChildItems.Remove(child);

    if (this._owner != null)
    {
        child.SetParent(this._owner);
        child.SetOwner(this._owner.Owner);
    }
    // etc
}

顺便说一句,ASP.NET和WinForms都是如此。对于WinForms,代码将略有不同。

Ahaaaa,这是一个非常微妙的细节。我永远不会想到这一点。