yield break in c#
This question already has an answer here:
Talking about C#
, If you want to write an iterator that returns nothing if the source is null or empty. Here is an example:
public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
if (source == null)
yield break;
foreach (T item in source)
yield return item;
}
It becomes impossible to return an empty set inside an iterator without the yield break
. Also it specifies that an iterator has come to an end. You can think of yield break
as return statement which does not return value.
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++;
}
链接地址: http://www.djcxy.com/p/54336.html
下一篇: 在C#中的收益率突破