yield return语句返回集合的一个元素,并移动到下一个元素上。yield break可停止迭代。包含yield语句的方法或属性也称为迭代块。迭代块必须声明为返回IEnumerator或IEnumerable接口。这个块可以包含多个yield return语句或yield break语句,但不能包含return语句。
下面是事例
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
using System.Diagnostics;
namespace ConsoleTest
{
public class ConsoleTest
{
public static void Main( string [] args)
{
// Test 1.
// yield break.
// yield return.
#region Test 1
ListClass list = new ListClass();
foreach ( string i in list)
{
Console.Write(i);
}
#endregion
// Test 2 yield Iterator.
#region Test 2
Node < string > [] nodes = new Node < string > [ 8 ];
nodes[ 0 ] = new Node < string > ( " A " );
nodes[ 1 ] = new Node < string > ( " B " );
nodes[ 2 ] = new Node < string > ( " C " );
nodes[ 3 ] = new Node < string > ( " D " );
nodes[ 4 ] = new Node < string > ( " E " );
nodes[ 5 ] = new Node < string > ( " F " );
nodes[ 6 ] = new Node < string > ( " G " );
nodes[ 7 ] = new Node < string > ( " H " );
nodes[ 0 ].LeftNode = nodes[ 1 ];
nodes[ 0 ].RightNode = nodes[ 2 ];
nodes[ 1 ].RightNode = nodes[ 3 ];
nodes[ 2 ].LeftNode = nodes[ 4 ];
nodes[ 2 ].RightNode = nodes[ 5 ];
nodes[ 3 ].LeftNode = nodes[ 6 ];
nodes[ 3 ].RightNode = nodes[ 7 ];
BinaryTree < string > tree = new BinaryTree < string > (nodes[ 0 ]);
BinaryTreeScanInOrder < string > inOrder = new BinaryTreeScanInOrder < string > (tree);
foreach ( string item in inOrder.InOrder)
{
Console.WriteLine(item);
}
Console.ReadLine();
#endregion
}
}
#region For Test 1
public class ListClass : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return " With an iterator, " ;
yield return " more than one " ;
yield break ;
yield return " value can be returned " ;
yield return " . " ;
}
}
#endregion
#region For Test 2
public class Node < T >
{
public Node < T > LeftNode;
public Node < T > RightNode;
public T Item;
public Node(T item)
{
this .Item = item;
}
}
public class BinaryTree < T >
{
public Node < T > Root;
public BinaryTree(Node < T > root)
{
this .Root = root;
}
}
public class BinaryTreeScanInOrder < T >
{
private BinaryTree < T > _binaryTree;
public BinaryTreeScanInOrder(BinaryTree < T > binaryTree)
{
this ._binaryTree = binaryTree;
}
public IEnumerable < T > InOrder
{
get
{
return ScanInOrder(_binaryTree.Root);
}
}
public IEnumerable < T > ScanInOrder(Node < T > root)
{
if (root.LeftNode != null )
{
foreach (T item in ScanInOrder(root.LeftNode))
{
yield return item;
}
}
yield return root.Item;
if (root.RightNode != null )
{
foreach (T item in ScanInOrder(root.RightNode))
{
yield return item;
}
}
}
}
#endregion
}