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

前端 未结 9 524
情歌与酒
情歌与酒 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:00

    You can't modify a collection while it's being enumerated. The second example only updates a property of the object, which is entirely different.

    Use a for loop if you need to add/remove/modify elements in a collection:

    for (int i = 0; i < MyObjectList.Count; i++)
    {
        MyObjectList[i] = new MyObject();
    }
    

提交回复
热议问题