Why can't I modify the loop variable in a foreach?

后端 未结 6 1578
孤城傲影
孤城傲影 2020-12-03 15:21

Why is a foreach loop a read only loop? What reasons are there for this?

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 16:05

    Not sure what you mean with read-only but I'm guessing that understanding what the foreach loop is under the hood will help. It's syntactic sugar and could also be written something like this:

    IEnumerator enumerator = list.GetEnumerator();
    while(enumerator.MoveNext())
    {
       T element = enumerator.Current;
       //body goes here
    }
    

    If you change the collection (list) it's getting hard to impossible to figure out how to process the iteration. Assigning to element (in the foreach version) could be viewed as either trying to assign to enumerator.Current which is read only or trying to change the value of the local holding a ref to enumerator.Current in which case you might as well introduce a local yourself because it no longer has anything to do with the enumerated list anymore.

提交回复
热议问题