How yield implements the pattern of lazy loading?

前端 未结 3 1250
清酒与你
清酒与你 2020-12-16 20:44

How yield implements the pattern of lazy loading?

3条回答
  •  温柔的废话
    2020-12-16 21:13

    Basically iterators implementated by using yield statements are compiled into a class that implements a state machine.

    If you never foreach (=iterate over and actually use) the returned IEnumerable, the code is never actually executed. And if you do, only the minimal code needed to determine the next value to return is executed, only to resume execution when a next value is requested.

    You can actually see this behavior happening when you single step such code in the debugger. Try it at least once: I think it's illuminating to see this happen step by step.

提交回复
热议问题