Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

前端 未结 9 561
情歌与酒
情歌与酒 2020-11-28 08:13

I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:

        foreach (var item in MyObj         


        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 09:01

    The point is that you cannot modify the collection itself while iterating over it. It is absolutely legal and common to modify the objects the iterator yields.

提交回复
热议问题