What does “yield break;” do in C#?

后端 未结 8 1961
南方客
南方客 2020-11-28 01:04

I have seen this syntax in MSDN: yield break, but I don\'t know what it does. Does anyone know?

8条回答
  •  隐瞒了意图╮
    2020-11-28 01:21

    Tells the iterator that it's reached the end.

    As an example:

    public interface INode
    {
        IEnumerable GetChildren();
    }
    
    public class NodeWithTenChildren : INode
    {
        private Node[] m_children = new Node[10];
    
        public IEnumerable GetChildren()
        {
            for( int n = 0; n < 10; ++n )
            {
                yield return m_children[ n ];
            }
        }
    }
    
    public class NodeWithNoChildren : INode
    {
        public IEnumerable GetChildren()
        {
            yield break;
        }
    }
    

提交回复
热议问题