Why are assignment operators (=) invalid in a foreach loop?

后端 未结 10 1196
栀梦
栀梦 2020-12-14 07:10

Why are assignment operators (=) invalid in a foreach loop? I\'m using C#, but I would assume that the argument is the same for other languages that support

10条回答
  •  独厮守ぢ
    2020-12-14 07:59

    Because you can't use a foreach loop to modify an array you're looping through. The loop iterates through the array, so if you try to modify what it's iterating through then unexpected behavior may occur. Furthermore, as Darin and DMan have pointed out, you're iterating through an IEnumerable which is itself read-only.

    PHP makes a copy of the array in its foreach loop and iterates through that copy, unless you use references, in which case you'll modify the array itself.

提交回复
热议问题