Does Foreach Cache IEnumerable?

后端 未结 2 387
耶瑟儿~
耶瑟儿~ 2021-01-18 02:36

Supposing that SomeMethod has signature

public IEnumerable SomeMethod();

is there any difference between

2条回答
  •  忘掉有多难
    2021-01-18 03:14

    Assuming you're talking about C#.

    foreach translates into something like this:

    var enumerable = SomeMethod(); // Or whatever is passed to foreach
    var enumerator = enumerable.GetEnumerator();
    
    while (enumerator.MoveNext())
    {
    ...
    }
    

    So, as enumerable is needed only once, there will be only one call to SomeMethod even if you put it directly into the foreach statement.

提交回复
热议问题