Difference between foreach and for loops over an IEnumerable class in C#

后端 未结 7 979
有刺的猬
有刺的猬 2020-12-17 17:00

I have been told that there is a performance difference between the following code blocks.

foreach (Entity e in entityList)
{
 ....
}

and <

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 17:10

    foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.

    They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator.

提交回复
热议问题