Is foreach purely “syntactic sugar”?

前端 未结 5 1401
南旧
南旧 2020-12-06 10:32

The compiler compiles a foreach loop into something like a for loop when the foreach is used with an array. And the compiler compile

5条回答
  •  粉色の甜心
    2020-12-06 11:09

    It is syntactic sugar. However, note that foreach works by calling GetEnumerator(), then MoveNext() until there is no further item returned and then always calls Dispose() on the enumerator it previously obtained. If you want to do it the same way, don't forget that Dispose()!

    Also, the CLR does some tricks related to getting the enumerator. See here and here, for example.

提交回复
热议问题