这部分代码是如何工作的
UPD。 你好, 我知道下面的代码是如何工作的。我知道cross和circle分别指向Cross()和Circle()方法。但我仍然对这部分代码感到困惑。你能为我解释一下吗?
public GameMoves()
{
cross = Cross();
circle = Circle();
}
所有代码
static void Main(string[] args)
{
GameMoves game = new GameMoves();
IEnumerator enumerator = game.Cross();
while (enumerator.MoveNext())
{
enumerator = (IEnumerator)enumerator.Current;
}
}
}
public class GameMoves
{
private IEnumerator cross;
private IEnumerator circle;
public GameMoves()
{
cross = Cross();
circle = Circle();
}
private int move = 0;
public IEnumerator Cross()
{
while (true)
{
Console.WriteLine("X, step {0}", move);
move++;
if (move > 9)
yield break;
yield return circle;
}
}
public IEnumerator Circle()
{
while (true)
{
Console.WriteLine("O, step {0}", move);
move++;
if (move > 9)
yield break;
yield return cross;
}
}
}
UPD.
Hello,
I know how code below is working. I know that cross, and circle are pointing to Cross(), and Circle() method. But I am still filling little confuse with this part of code. Can you explain it for me?
public GameMoves()
{
cross = Cross();
circle = Circle();
}
All code
static void Main(string[] args)
{
GameMoves game = new GameMoves();
IEnumerator enumerator = game.Cross();
while (enumerator.MoveNext())
{
enumerator = (IEnumerator)enumerator.Current;
}
}
}
public class GameMoves
{
private IEnumerator cross;
private IEnumerator circle;
public GameMoves()
{
cross = Cross();
circle = Circle();
}
private int move = 0;
public IEnumerator Cross()
{
while (true)
{
Console.WriteLine("X, step {0}", move);
move++;
if (move > 9)
yield break;
yield return circle;
}
}
public IEnumerator Circle()
{
while (true)
{
Console.WriteLine("O, step {0}", move);
move++;
if (move > 9)
yield break;
yield return cross;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cross
和Circle
都是生成器。它们通过IEnumerable
返回一个对象
序列。也就是说,您可以编写:在每次循环迭代中,下一个要返回的元素在
Cross
或Circle
方法内生成。这些方法不会一次全部执行,而是每次到达yield return
语句时,程序都会在调用代码(foreach
循环)中继续执行,并且仅当需要下一个项目时,才会恢复生成器内的代码。PS:在我的互联网连接中断几个小时之前,我还想评论一个奇怪的事实,即您的生成器不断通过
yield return
返回对自身的引用。老实说,这对我来说确实没有意义。我从未见过这种代码,我想知道它是否真的有用?Both
Cross
andCircle
are generators. They return a sequence ofobject
s by means of anIEnumerable
. That is, you could write:And on every loop iteration, the next element to be returned is generated inside the
Cross
orCircle
method. Those methods don't execute all at a time, instead each time ayield return
statement is reached, program execution will continue in the calling code (theforeach
loop), and the code inside the generator is only resumed when the next item is needed.P.S.: Before my internet connection broke down for some hours, I had also wanted to comment on the strange fact that your generators keeps returning references to themselves via
yield return
. That doesn't really make sense to me, to be honest; I've never seen that kind of code and I wonder if it actually does something useful?