【问题标题】:Getting "Collection was modified " error even though I'm modifying a different collection即使我正在修改不同的集合,也会出现“集合已修改”错误
【发布时间】:2012-10-31 06:21:23
【问题描述】:

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

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

谁能解释一下为什么?

【问题讨论】:

    标签: c# asp.net collections


    【解决方案1】:

    当您将MenuItem 添加到另一个MenuItemCollection 时,它会从其所有者(即mainMenu)中删除。因此原始集合被修改:

    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 的代码会略有不同。

    【讨论】:

    • 啊啊啊,这是一个非常微妙的细节。我永远也猜不到。
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2011-09-12
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多