foreach循環中不能修改集合元素的值,否則會報錯:Collection was modified; enumeration operation may not execute.
當用foreach遍歷Collection時,如果對Collection有Add或者Remove操作或者給item某個屬性賦值都會有這個錯誤。
原因是因為Collection返回的IEnumerator把當前的屬性暴露為只讀屬性,所以對其的修改會導致運行時錯誤,只需要把foreach改為for來遍歷就好了。
foreach循環中不能修改集合元素的值,否則會報錯:Collection was modified; enumeration operation may not execute.
當用foreach遍歷Collection時,如果對Collection有Add或者Remove操作或者給item某個屬性賦值都會有這個錯誤。
原因是因為Collection返回的IEnumerator把當前的屬性暴露為只讀屬性,所以對其的修改會導致運行時錯誤,只需要把foreach改為for來遍歷就好了。
本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。