What does "yield break;" do in C#?
I have seen this syntax in MSDN: yield break
, but I don't know what it does. Does anyone know?
It specifies that an iterator has come to an end. You can think of yield break
as a return
statement which does not return a value.
For example, if you define a function as an iterator, the body of the function may look like this:
for (int i = 0; i < 5; i++)
{
yield return i;
}
Console.Out.WriteLine("You will see me");
Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.
Or like this with yield break
:
int i = 0;
while (true)
{
if (i < 5)
{
yield return i;
}
else
{
// note that i++ will not be executed after this
yield break;
}
i++;
}
Console.Out.WriteLine("Won't see me");
In this case the last statement is never executed because we left the function early.
结束迭代器块(例如,说IEnumerable中没有更多元素)。
Tells the iterator that it's reached the end.
As an example:
public interface INode
{
IEnumerable<Node> GetChildren();
}
public class NodeWithTenChildren : INode
{
private Node[] m_children = new Node[10];
public IEnumerable<Node> GetChildren()
{
for( int n = 0; n < 10; ++n )
{
yield return m_children[ n ];
}
}
}
public class NodeWithNoChildren : INode
{
public IEnumerable<Node> GetChildren()
{
yield break;
}
}
链接地址: http://www.djcxy.com/p/170.html
上一篇: 如何创建一个不存在的目录?
下一篇: 什么是“产量突破”? 在C#中做?