【问题标题】:C# - How to Stop a Loop When a Key is Pressed? [duplicate]C# - 按下键时如何停止循环? [复制]
【发布时间】:2017-05-23 08:57:53
【问题描述】:

目前我正在使用此代码:

using System;

namespace Project
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            bool key = false;
            while (key == false)
            {
                Console.WriteLine ("Loop");
            }
        }
    }
}

这很好用,但我想让循环在按下一个键时停止。我试过这个:

using System;

namespace Project
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            bool key = false;
            while (key == false)
            {
                Console.WriteLine ("Loop");
                {
                Console.ReadKey (true);
                key = true
                }
            }
        }
    }
}

但这只是在按下一个键时继续循环。有什么解决办法吗?

【问题讨论】:

  • 你的第二个代码没有编译,也没有继续循环(它只是阻塞按键)。

标签: c# loops


【解决方案1】:

我建议使用Console.KeyAvailable:

 while (!Console.KeyAvailable) {
   Console.WriteLine("Loop");
 }

【讨论】:

  • 感谢您的帮助!效果很好!
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 2022-11-21
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2023-03-13
相关资源
最近更新 更多