When writing an enumerable, what does yield return var?

Possible Duplicate:
What is the yield keyword used for in C#?

Say I have code that looks like:

(steam is a filestream)

using(BinaryWriter bw = new BinaryWriter(stream))
{
  foreach(byte[] b in BreakBytes(objectOfBytes))
  {
    writer.Write(b);
  }
}

So for BreakBytes to work, it has to do something like:

public static IEnumerable<byte[]> BreakBytes(byte[] b)
{
  ..
  while(..) {

     yield return some_buffer;

  }
  ..
}

What exactly is yield doing? Does it keep track of where it was position wise?

I believe it is return to the calling foreach loop, but continues to the next iteration when called again?


简而言之,该方法中的代码被重写为一个状态机,它可以像您怀疑的那样执行:它会跟踪它在循环中的位置,返回给调用者并继续停止。


yield is really special in C# as it doesn't follow normal flow of control.

When iterating the returned IEnumerable , the BreakBytes function will be called and run until it has yielded a value. Control will then be passed back to the foreach loop. When the loop steps to the next item, BreakBytes is resumed and run until it hits another yield .

This somewhat odd construct gives the benefit that if only part of the IEnumerable is enumerated, only that part needs to be generated.


Jon Skeet can tell you all about them: http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx

Yes. It keeps track of its internal state.

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

上一篇: 收益的有用性

下一篇: 在编写一个枚举时,什么产生return var?