在迭代期间从SortedList中删除是否安全

Cap*_*mic 3 .net c# ienumerator

我的问题是枚举器从SortedList中删除项目是否安全?

SortedList<decimal, string> myDictionary;
// omitted code

IEnumerator<decimal, string> enum = myDictionary.GetEnumerator();

while(enum.MoveNext)
{
  // is it ok to remove here?
  myDictionary.Remove(enum.Current.Key);
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 8

这将抛出异常 - 您无法在迭代时修改集合.

如果你仔细想一想,你会理解为什么.如果允许在集合中添加或删除,则不再迭代同一集合 - 您要么太多(添加),要么没有足够的项目(删除).