用 C# 中的开关替换 if 语句

卢克

这里我有一个在 while 循环中调用的函数。我很确定可以使用 switch 语句优化代码,但我就是想不通?请帮我整理这段代码。

我是使用 ConsoleApp 进行编码的新手,所以我只是制作了一个基本程序来记录您的键,稍后我将使用它来创建一个 GUI,通过箭头键导航。

除了最后的 else 语句外,其他所有语句都是针对特定键(例如 Escape、Enter 和 Spacebar)进行的。这是因为在“KeyChar”中无法识别这些特殊键以及许多其他键。所有数字和字母都属于“KeyChar”。

void ifcheck()
        {
            ConsoleKeyInfo key = Console.ReadKey();
            if (key.Key == ConsoleKey.Escape)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("eStopping.. (0x0)");
                power = false;
            }
            else if (key.Key == ConsoleKey.Enter)
            {
                Console.WriteLine("\n" + "[----" + "Enter" + "----" + " Was pressed]");
            }
            else if (key.Key == ConsoleKey.Spacebar)
            {
                Console.WriteLine("\n" + "[----" + "Spacebar" + "----" + " Was pressed]");
            }
            else if (key.Key == ConsoleKey.Tab)
            {
                Console.WriteLine("\n" + "[----" + "Tab" + "----" + " Was pressed]");
            }
            else
            {
                Console.WriteLine("\n" + "[----" + key.KeyChar + "----" + " Was pressed]");
            }            
        }
达伦彼得森

尝试这个:

void ifcheck()
    {
        ConsoleKeyInfo key = Console.ReadKey();
        switch (key.Key)
        {
            case ConsoleKey.Escape:
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("eStopping.. (0x0)");
                power = false;
                break;
             default:
                Console.WriteLine("\n" + "[----" + key.KeyChar + "----" + " Was pressed]");
                break;
        }
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章