【发布时间】:2011-08-08 23:04:33
【问题描述】:
我正在尝试使用 C# 编写一个程序,该程序基本上基于用户按下的键(例如 X = 退出、D = 断开连接等;)通过使用 Console.ReadKey();在c#中
我遇到的问题是如何在 Switch 语句中使用 ReadKey 信息。有人可以帮忙吗?代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Switch_Test
{
class Program
{
static void Main()
{
Console.WriteLine("Welcome. Please enter your command: ");
string chinput;
int input;
bool activated = false;
input = Console.ReadKey();
chinput = Convert.ToChar(input);
switch (chinput)
{
case 'x':
{
Console.WriteLine("You pressed x...");
break;
}
case 'y':
{
Console.WriteLine("You pressed y..");
break;
}
case 'd':
{
if (activated != true)
{
Console.WriteLine("Please activate first!");
break;
}
else
{
Console.WriteLine("Active..");
break;
}
}
case 'a':
{
if (activated != true)
{
activated = true;
Console.WriteLine("Activating..");
break;
}
else
{
activated = false;
Console.WriteLine("Deactivating.");
break;
}
}
default:
Console.WriteLine("Unknown Command.");
break;
}
}
}
}
我知道这可能真的错了,但我最初是从 Console.ReadLine(); 开始的。 ,唯一的区别是我希望它在您按下单个键时激活一个功能,而不是必须按回车键或能够输入不同的键。提前致谢!
【问题讨论】:
标签: c# switch-statement