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

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

    Because the first one doesn't make much sense, basically. The variable item is controlled by the iterator (set on each iteration). You shouldn't need to change it- just use another variable:

    foreach (var item in MyObjectList)
    {
        var someOtherItem = Value;
    
        ....
    }
    

    As for the second, there are valid use cases there- you might want to iterate over an enumeration of cars and call .Drive() on each one, or set car.gasTank = full;

提交回复
热议问题