首页 > 解决方案 > C# 监听键并输出结果

问题描述

我有以下代码根据我按下的键输出 Meow 或 Awo。

它正在工作,但由于某种原因,在 do/while 的第一次迭代之后,我需要在 c 和 d 上按两次以使其输出任何内容。关于我如何以不同的方式做到这一点的任何想法?

using System;

namespace Program
{
    interface Animal
    {
        void animalSound();
    }

    class Dog : Animal
    {
        public void animalSound()
        {
            Console.WriteLine(" Awo Awo!");
        }
    }

    class Cat : Animal
    {
        public void animalSound()
        {
            Console.WriteLine(" Meow");
        }
    }


    class Program
    {
        static void Main(string[] a)
        {
            Dog myDog = new Dog();
            Cat myCat = new Cat();
            Console.WriteLine("--------Press C to call the Cat--------");
            Console.WriteLine("--------Press D to call the Dog--------");
            Console.WriteLine("Press double ESC to close the program");

            do
            {
                Console.WriteLine("Starting the do loop 1");
                ConsoleKeyInfo KeyInfo = Console.ReadKey(true);
                while (!Console.KeyAvailable)
                {
                    Console.WriteLine("Starting the while loop 2");
                    if (KeyInfo.Key == ConsoleKey.C)
                    {
                        myCat.animalSound();
                    } else if(KeyInfo.Key == ConsoleKey.D) {
                        myDog.animalSound();
                    }
                    Console.WriteLine("Breaking the while loop 3");
                    break;
                }
                Console.WriteLine("Continue the do loop 4");
                continue;
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

        }


    }
}

标签: c#.net

解决方案


想要第二个条目

Console.ReadKey(true).Key

循环条件中的用户

尝试这个:

Dog myDog = new Dog();
Cat myCat = new Cat();
Console.WriteLine("--------Press C to call the Cat--------");
Console.WriteLine("--------Press D to call the Dog--------");
Console.WriteLine("Press double ESC to close the program");
ConsoleKeyInfo KeyInfo;
int counter = 1;
do
{
    KeyInfo = Console.ReadKey(true);

    Console.WriteLine("Starting the while loop " + counter);
    counter++;

    if (KeyInfo.Key == ConsoleKey.C)
    {
        myCat.animalSound();
    }
    else if (KeyInfo.Key == ConsoleKey.D)
    {
        myDog.animalSound();
    }
} while (KeyInfo.Key != ConsoleKey.Escape);

推荐阅读