yield 关键字向编译器指示它所在的方法是迭代器块。 编译器生成一个类来实现迭代器块中表示的行为。 在迭代器块中,yield 关键字与 return 关键字结合使用,向枚举器对象提供值。 这是一个返回值,例如,在 foreach 语句的每一次循环中返回的值。 yield 关键字也可与 break 结合使用,表示迭代结束。 有关迭代器的更多信息,请参见迭代器(C# 编程指南)。 下面的示例演示两种形式的 yield 语句。
示例:
1 |
<ol class="dp-c"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> List </span></span></li><li><span>{ </span></li><li class="alt"><span> <span class="comment">//using System.Collections;</span><span> </span></span></li><li><span> <span class="keyword">public</span><span> </span><span class="keyword">static</span><span> IEnumerable Power(</span><span class="keyword">int</span><span> number, </span><span class="keyword">int</span><span> exponent) </span></span></li><li class="alt"><span> { </span></li><li><span> <span class="keyword">int</span><span> counter = 0; </span></span></li><li class="alt"><span> <span class="keyword">int</span><span> result = 1; </span></span></li><li><span> <span class="keyword">while</span><span> (counter++ < exponent) </span></span></li><li class="alt"><span> { </span></li><li><span> result = result * number; </span></li><li class="alt"><span> yield <span class="keyword">return</span><span> result; </span></span></li><li><span> } </span></li><li class="alt"><span> } </span></li><li><span> </span></li><li class="alt"><span> <span class="keyword">static</span><span> </span><span class="keyword">void</span><span> Main() </span></span></li><li><span> { </span></li><li class="alt"><span> <span class="comment">// Display powers of 2 up to the exponent 8:</span><span> </span></span></li><li><span> <span class="keyword">foreach</span><span> (</span><span class="keyword">int</span><span> i </span><span class="keyword">in</span><span> Power(2, 8)) </span></span></li><li class="alt"><span> { </span></li><li><span> Console.Write(<span class="string">"{0} "</span><span>, i); </span></span></li><li class="alt"><span> } </span></li><li><span> } </span></li><li class="alt"><span>} </span></li><li><span><span class="comment">/*</span> </span></li><li class="alt"><span><span class="comment">Output:</span> </span></li><li><span><span class="comment">2 4 8 16 32 64 128 256 </span> </span></li><li class="alt"><span><span class="comment">*/</span><span> </span></span></li></ol> |