初学问题书上一段代码没弄懂那位大哥指点一下
看C#高级编程中有一段代码,没看明白是怎么运行的问题是在new Game()时执行构造函数时,调用了Cross和Circle方法,还要IEnumerator enumerator=game.Cross();这句也调用了Cross方法,此时为什么不打印出信息,而是在while中打印出信息,在迭代的过程中并没有直接调用这两个方法却打印此方法中的信息,怎么理解?
哪位大哥能详细地解释一下整个过程是怎么执行的,不知道我哪里理解得不对,总是不能明白
谢谢!!
程序代码:
using System;
using System.Collections;
namespace Myspace.Test
{
public class Myclass
{
public static void Main()
{
Game game=new Game();
Console.WriteLine("hello world");
IEnumerator enumerator=game.Cross();
while(enumerator.MoveNext())
{
enumerator=(IEnumerator)enumerator.Current;
}
return;
}
}
public class Game
{
private IEnumerator cross;
private IEnumerator circle;
public Game()
{
cross=Cross();
circle=Circle();
}
private int move =0;
public IEnumerator Cross()
{
while(true)
{
Console.WriteLine("Cross,move {0}",move);
move++;
if (move>9){
yield break;
}else {
yield return circle;
}
}
}
public IEnumerator Circle()
{
while(true)
{
Console.WriteLine("Circle move {0}",move);
move++;
if(move>9){
yield break;
}else {
yield return cross;
}
}
}
}
}
运行结果
程序代码:hello world Cross,move 0 Circle move 1 Cross,move 2 Circle move 3 Cross,move 4 Circle move 5 Cross,move 6 Circle move 7 Cross,move 8 Circle move 9







