yield statement implementation

I want to know everything about the yield statement, in an easy to understand form.

I have read about the yield statement and its ease when implementing the iterator pattern. However, most of it is very dry. I would like to get under the covers and see how Microsoft handles return yield.

Also, when do you use yield break?


yield works by building a state machine internally. It stores the current state of the routine when it exits and resumes from that state next time.

You can use Reflector to see how it's implemented by the compiler.

yield break is used when you want to stop returning results. If you don't have a yield break , the compiler would assume one at the end of the function (just like a return; statement in a normal function)


Here's a start, from Raymond Chen's blog:

  • The implementation of iterators in C# and its consequences (part 1)
  • The implementation of iterators in C# and its consequences (part 2)
  • The implementation of iterators in C# and its consequences (part 3)

  • As Mehrdad says, it builds a state machine.

    As well as using Reflector (another excellent suggestion) you might find my article on iterator block implementation useful. It would be relatively simple if it weren't for finally blocks - but they introduce a whole extra dimension of complexity!

    链接地址: http://www.djcxy.com/p/1588.html

    上一篇: 我如何用C#计算某人的年龄?

    下一篇: yield语句实现