switch判断中多个case的简单优化

Posted liezhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了switch判断中多个case的简单优化相关的知识,希望对你有一定的参考价值。

在开发中做一个简单的计算器控件,每一个数字键对应触发每一个不同的Win32API命令。用到switch case的多个判断写法,感觉代码这样子写法不太好,用字节数组下标的方法稍微修改了一下。       

               switch (btn.Content.ToString())
               
                    case "0":
                        Win32API.AddKeyBoardINput(0x30);
                        break;
                    case "1":
                        Win32API.AddKeyBoardINput(0x31);
                        break;
                    case "2":
                        Win32API.AddKeyBoardINput(0x32);
                        break;
                    case "3":
                        Win32API.AddKeyBoardINput(0x33);
                        break;
                    case "4":
                        Win32API.AddKeyBoardINput(0x34);
                        break;
                    case "5":
                        Win32API.AddKeyBoardINput(0x35);
                        break;
                    case "6":
                        Win32API.AddKeyBoardINput(0x36);
                        break;
                    case "7":
                        Win32API.AddKeyBoardINput(0x37);
                        break;
                    case "8":
                        Win32API.AddKeyBoardINput(0x38);
                        break;
                    case "9":
                        Win32API.AddKeyBoardINput(0x39);
                        break;
                    case "X":
                        Win32API.AddKeyBoardINput(0X58);
                        break;
               

修改为:

       byte[] array = new byte[] 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x08 ;
        private void Button_Click(object sender, RoutedEventArgs e)
       
            if (e.Source is Button)
           
                var btn = sender as Button;
                int num = int.Parse(btn.Content.ToString());
                Win32API.AddKeyBoardINput(array[num]);
           
       

以上是关于switch判断中多个case的简单优化的主要内容,如果未能解决你的问题,请参考以下文章

优化:switch 语句中的 case 顺序重要吗? [关闭]

JavaScript 代码逻辑判断的优化

switch case语句和if的区别

有啥完美的方法替代java中的 if-else,switch-case

for-loop / switch-statement的性能优化

java多层if嵌套怎么优化