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]);
            }
        }

猜你喜欢

转载自www.cnblogs.com/liezhong/p/11364132.html
0条评论
添加一条新回复
  
今日推荐