C# C听键并输出结果
根据我按下的键,我有以下代码来输出Meow或Awo 它正在工作,但由于某种原因,在第一次迭代do/之后,我需要在c和d上按两次,以使它输出任何内容。你知道我如何用不同的方式做吗C# C听键并输出结果,c#,.net,C#,.net,根据我按下的键,我有以下代码来输出Meow或Awo 它正在工作,但由于某种原因,在第一次迭代do/之后,我需要在c和d上按两次,以使它输出任何内容。你知道我如何用不同的方式做吗 using System; namespace Program { interface Animal { void animalSound(); } class Dog : Animal { public void animalSound()
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);
}
}
}
想要第二个来自
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);
我通过这样更改代码来解决我的小问题: 我去掉了第一道菜和最后一道菜,只保留了一道菜
KeyInfo = Console.ReadKey(true);
while (KeyInfo.Key != ConsoleKey.Escape)
{
animal = GwtAnimal(KeyInfo);
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.AnimalSound();
}
else if (KeyInfo.Key == ConsoleKey.D)
{
myDog.AnimalSound();
}
KeyInfo = Console.ReadKey(true);
}
以某种方式去掉第二个Console.ReadKey。@Sinatr你是说while条件中的那个吗?