c#中的收益率突破

时间:2012-11-23 06:23:48

标签: c# vb.net iterator

它有什么不同,只是从函数完成返回或让函数完成到底?注意VB.NET没有 yield break ,但要求函数使用 iterator 关键字标记。

1 个答案:

答案 0 :(得分:2)

谈论C#,如果你想编写一个迭代器,如果源为null或为空则不返回任何内容。这是一个例子:

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视为不返回值的return语句。

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++;
}    
相关问题