当用foreach遍历Collection时,如果对Collection有Add或者Remove操作时,会发生以下运行时错误:
"Collection was modified; enumeration operation may not execute." 如下所示:
究其原因,是因为Collection返回的IEnumerator把当前的属性暴露为只读属性,所以对其的修改会导致运行时错误,只需要把foreach改为for来遍历就好了。
对于Hashtable,由于没有提供[]操作符来供for遍历,可以先把item存入到一个array中,然后再对其进行Remove或Add操作,如下: