控制台应用程序中的c#菜单
您好,我正在尝试制作一个指令菜单,我想获取指令编号作为继续的输入。这是我的密码:控制台应用程序中的c#菜单,c#,menu,C#,Menu,您好,我正在尝试制作一个指令菜单,我想获取指令编号作为继续的输入。这是我的密码: class Program { static void Main(string[] args) { Console.WriteLine("please choose one of the numbers below : "+"\n"); Console.WriteLine("1.adding new student"+"\n"); Console.W
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please choose one of the numbers below : "+"\n");
Console.WriteLine("1.adding new student"+"\n");
Console.WriteLine("2.adding new course"+"\n");
Console.WriteLine("3.adding new grade"+"\n");
Console.WriteLine("4.showing the best student"+"\n");
Console.WriteLine("5.getting students average"+"\n");
Console.WriteLine("5.exit"+"\n");
Console.ReadKey();
if(ConsoleKey="1")
{
}
Console.ReadKey();
}
那么,如果用户选择数字1,我如何进入下一步呢?因为我知道给Console.Readkey()分配一个数字是错误的。您可以使用
Console.ReadLine()
,它会给您一个字符串,您可以以任何方式验证/处理它
无论如何,您也可以使用Console.ReadKey()的返回值
它返回一个ConsoleKeyInfo
,因此您可以执行如下操作:
if (Console.ReadKey().Key == ConsoleKey.D1) { /* key '1' pressed */ }
这里有ConsoleKey
enum的完整文档:您使用的方法不正确,没有存储函数调用返回的值,因此根本无法比较它的值。其次,正如David所提到的,在C#中使用=
,而不是=
,这是一个赋值运算符。考虑使用这个,
// For this approach, you would have to limit the values to one character.
if(Console.ReadLine() == "1")
{
// 1 was pressed
}
否则,请使用以下代码
if(Console.ReadKey().Key == ConsoleKey.D1)
{
// 1 was pressed
}
一个常见的例子是在程序结束时使用Console.ReadKey()
,以防止终端关闭,并记住数据丢失。您可以随时比较这些值并查看输入的值,有关更多信息,请参阅以下内容:
Use Console.ReadLineReadKey返回一个值:您可以在比较中使用该值(或其属性)。(顺便说一句,比较是用=
,而不是=
)