它除了从返回或让函数完成到最后之外,还有什么不同吗?注意 VB.NET 没有产量中断,但要求函数使用迭代器关键字进行标记。
说C#
,如果你想写一个在源为空或空的情况下不返回任何内容的迭代器。下面是一个示例:
public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
if (source == null)
yield break;
foreach (T item in source)
yield return item;
}
如果没有yield break
,就不可能在迭代器中返回一个空集。此外,它还指定迭代器已结束。您可以将yield break
视为不返回值的返回语句。
int i = 0;
while (true)
{
if (i < 5)
yield return i;
else
yield break; // note that i++ will not be executed after this statement
i++;
}