如何跳出这个循环?

How to get out of this cycle?

一天中的好时光!问题是循环:写代码的最后2行被定义为无法访问的代码,因为当你按下任意键的情况下会开始无限循环。编程经验少,不懂。如何跳出这个循环?这是程序的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace ConsoleApplication3
    {
    class Hero
    {
        public int x = 0;
        public int y = 0;
        public int hp = 3;
        public double power = 3;
        public void printHero()
        {
            Console.WriteLine(" x={0},y={1},hp={2},power={3}", x, y, hp, power);
        }
        public void hitHero()
        {
            hp = hp - 1;
        }
        public void attackHero()
        {
            power = power - 0.5;
        }
        static void Main(string[] args)
        {
            Hero hero;
            hero = new Hero();
            ConsoleKeyInfo keypress;
            keypress = Console.ReadKey();
            while (true)
            {
                switch (keypress.KeyChar)
                {
                    case 'A':
                        hero.x = hero.x - 1;
                        hero.printHero();
                        break;
                    case 'D':
                        hero.x = hero.x +1;
                        hero.printHero();
                        break;
                    case 'W':
                        hero.y = hero.y + 1;
                        hero.printHero();
                        break;
                    case 'S':
                        hero.y = hero.y - 1;
                        hero.printHero();
                        break;
                    case 'E':
                        hero.attackHero();
                        hero.printHero();
                        break;
                    case 'X':
                        hero.hitHero();
                        hero.printHero();
                        break;
                    default:
                        break;
                }
            } 
            Console.ReadLine();
            return;
        }
    }
}

嗯,总有 break 命令。您可以在按下某个键后标记您想要中断。然后在switch之外,你break。但是,为什么你仍然需要一个 while(true) 循环?

您必须在 循环中查询键

while (true)
{
    keypress = Console.ReadKey(); // continuously check for key presses
    switch (keypress.KeyChar) // process new keypresses
    {
        case 'A':
...

并且不要忘记在某些时候打破循环(例如,当满足某些条件或按下某个键时):

...

    if(endCondition)
        break; // will exit while(true)
}