foreach中不能修改元素的值

foreach循环中不能修改集合元素的值,否则会报错:Collection was modified; enumeration operation may not execute.

当用foreach遍历Collection时,如果对Collection有Add或者Remove操作或者给item某个属性赋值都会有这个错误。

原因是因为Collection返回的IEnumerator把当前的属性暴露为只读属性,所以对其的修改会导致运行时错误,只需要把foreach改为for来遍历就好了。

你可能感兴趣的:(foreach)