通过无限循环示例在C#中产生

时间:2014-03-17 08:47:24

标签: c# loops state yield

我试图理解收益率如何在C#中起作用。为了测试我做了一些示例代码:

using System;
using System.Text;

namespace ConsoleApplication1
{
    class GameFrame
    {
    };

    class GameState
    {
        public static GameFrame Begin()
        {
            Console.WriteLine("GameState.Begin");

            return new GameFrame();
        }

        public static GameFrame Play()
        {
            Console.WriteLine("GameState.Play");

            return new GameFrame();
        }

        public static System.Collections.Generic.IEnumerator<GameFrame> MainLoop()
        {
            yield return Begin();

            while (true)
            {
                yield return Play();
            }
        }
    };


    class Program
    {
        static void Main()
        {
            while (GameState.MainLoop() != null)
            {
            }
        }
    }
}

此代码仅尝试运行一次Begin函数并调用无限次函数Play。请告诉我为什么我从未在控制台中看到我的消息?

3 个答案:

答案 0 :(得分:12)

您需要枚举集合,只需检查结果是否为null,否则将无法启动枚举。

foreach (var frame in GameState.MainLoop())
{
    //Do whatever with frame
}

要使其与`foreach一起使用,您可以使MainLoop方法返回IEnumerable<GameFrame>而不是IEnumerator<GameFrame>或者只使用

var enumerator = GameState.MainLoop();
while (enumerator.MoveNext())
{
     //Do whatever with enumerator.Current
}

答案 1 :(得分:1)

那是因为你回来了IEnumerable<GameFrame>,但从未真正反复过来。

请改为尝试:

var frames = GameState.MainLoop();
foreach(var frame in frames)
{
    // use the frame
    // e.g. frame.Show(); (note: in your example code, 
    // GameFrame doesn't have any members)
}

答案 2 :(得分:1)

GameState.MainLoop()返回IEnumerable,它代表无限集合,您可以从中获取项目。当您使用yield时,元素仅在需要时才会被评估,因此只有当您触摸&#34;时才会看到一些输出。和项目

 GameState.MainLoop().Take(5).ToList();

我建议不要使用带有无限循环的foreach。