public class GameMoves
{
private IEnumerator cross;
private IEnumerator circle;
public GameMoves()
{
cross = Cross();
circle = Circle();
}
private int move = 0;
const int MaxMoves = 9;
public IEnumerator Cross()
{
Console.WriteLine("Test");
while (true)
{
Console.WriteLine("Cross, move {0}", move);
if (++move >= MaxMoves)
yield break;
yield return circle;
}
}
/// <summary>
/// 给Foreach用
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
while (true)
{
move++;
if (move >= MaxMoves)
yield break;
yield return circle;
}
}
public IEnumerator Circle()
{
while (true)
{
Console.WriteLine("Circle, move {0}", move);
if (++move >= MaxMoves)
yield break;
yield return cross;
}
}
}
private static void Main(string[] args)
{
var game = new GameMoves();
IEnumerator enumerator = game.Cross();
while (enumerator.MoveNext())
{
enumerator = enumerator.Current as IEnumerator;
}
}
运行结果:
图中只出现了两个Test,那是因为第一次 IEnumerator enumerator = game.Cross();创建的时候,调用MoveNext运行一次,接着当运行到第二次的Cross的时候运行一次,是因为IEnumerator enumerator = game.Cross();和yield return cross两个对象不是同一个,而之后的cross是一样的所以接着前面的cross继续循环下去(在while里面执行),不会从Cross函数开始处执行,导致接下去的输出不会有Test