Collection was modified; enumeration operation may not execute - why?

前端 未结 7 1778
南方客
南方客 2020-11-30 11:38

I\'m enumerating over a collection that implements IList, and during the enumeration I am modifying the collection. I get the error, \"Collection was modified; enumeration

7条回答
  •  暖寄归人
    2020-11-30 11:55

    I assume the reason is that the state of the enumerator object is related to the state of the collection. For example a list enumerator would have an int field to store the index of the current element. However if you remove an element from the list you are shifting all the indexes after the element left by one. At this point the enumerator would skip an object thus manifesting wrong behaviour. Making the enumerator valid for all possible cases would require complex logic and can hurt performance for the most common case (not changing the collection). I believe this is why the designers of the collections in .NET decided that they should just throw an exception when the enumerator is in invald state instead of trying to fix it.

提交回复
热议问题