集合已修改,枚举可能无法继续

Collection was modified, enumeration may not continue

我有以下代码

public bool Notify(bool filterStatus)
{
   foreach (IFilterStatusListener listener in listeners)
   {
      listener.Update(filterStatus);
   }
   return true;
}

方法 Update 为 Children

递归调用 Notify
public void Update(bool status)
{
   this.isFilteredFixed = false;
   this.Notify(status);
   this.RaisePropertyChanged("IsFiltered");
}

当我 运行 这段代码时,出现以下错误

我该怎么办?

foreach 期望集合保持不变。您可以尝试使用普通的 for 循环。

MSDN:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

当您使用 foreach 语句迭代集合时,您无法更改正在迭代的集合,因为迭代器会迷失在它实际所在的位置。

有几种解决方法:

  • 您使用 for 循环进行迭代
  • 您创建了您正在迭代的集合的副本并对其进行处理。