How yield
implements the pattern of lazy loading
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
If you want to know more about what the compiler is doing when using
yield return
, check this article by Jon Skeet: Iterator block implementation detailsBasically 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 returnedIEnumerable<T>
, 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.
yield implementation doesn't reach the code until it's needed.
For example, this code:
Will actually compile into a nested class which implements
IEnumerable<int>
and the body ofGetInts()
will return an instance of that class.Using reflector you can see:
Edit - adding more info about
GetInts
implementation:The way this implementation makes it lazy is based on the
Enumerator
MoveNext()
method. When the enumerable nested class is generated (<GetInts>d__6d
in the example), it has a state and to each state a value is connected (this is a simple case, in more advanced cases the value will be evaluated when the code reach the state). If we take a look in theMoveNext()
code of<GetInts>d__6d
we'll see the state:When the enumerator is asked for the current object it returns the object which is connected to the current state.
In order to show that the code is evaluated only when it's required you can look at this example:
I hope it's a bit more clear. I recommend to take a look at the code with Reflector and observe the compiled code as you change the "yield" code.