开发者

C# foreach - Is collection computed with each iteration? [duplicate]

This question already has answers here: 开发者_开发知识库 Closed 12 years ago.

Possible Duplicate:

How does foreach work when looping through function results?

Title has the heart of the question in it. Here's an example scenario to flesh it out some more.

foreach(something thing in GetSomethings())
{ dosomething }

Lets say GetSomethings has side effects. Will GetSomethings be executed once or will it get executed for each time the loop iterates?


Foreach uses IEnumerable interface, it retrieves the Enumerator once, and uses it to traverse the collection.

So it's perfectly safe to use foreach on a complex function, it doesn't re-calculate the collection each time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜