代码之家  ›  专栏  ›  技术社区  ›  RKh

为什么一个开关…案件不采取'字符'?

c#
  •  1
  • RKh  · 技术社区  · 15 年前

    我对这个代码有两个问题:

    public int InsertOrUpdateRecord(char _code, string _databaseFileName)
    {
    
       switch(_code)
       {
          case 'N':
               // Some code here
    
           case 'U':
               // Some code here
       }
           return 0;
    }
    
    1. 它不接受 烧焦 单引号和双引号值。
    2. 如果我将代码作为 一串 ,它在 案例 出现此错误时:

    控件不能通过一个事例标签落到另一个事例标签上。

    5 回复  |  直到 15 年前
        1
  •  14
  •   Elisha    15 年前

    编译错误的原因是 case 错过了 break

    switch (_code)
    {
        case 'N':
        // Some code here
            break; // break that closes the case
    
        case 'U':
        // Some code here
            break; // break that closes the case
    }
    
        2
  •  2
  •   nbro kai    11 年前

    你需要做一个 break 在本案结束时:

    switch (_code)
    {
        case 'N':
            // Some code here
            Console.WriteLine("N was passed");
            break;
        case 'U':
            // Some code here
            Console.WriteLine("U was passed");
            break;
    }
    
        3
  •  0
  •   Will Marcouiller    15 年前

    除非你想在两种情况下都这样做:

    switch(_char) {
        case 'N':
        case 'U':
          // Common code for cases N and U here...
    }
    

    必须明确告诉编译器case语句停止的位置:

    switch(_char) {
        case 'N':
            // Code here...
            break; // The N case ends here.
        case 'U':
            // Code here with different behaviour than N case...
            break; // The U case ends here. 
    }
    

    这个 break 语句告诉编译器您已经完成了该案例,并且它必须从 switch 指示。

        4
  •  0
  •   S Anil Dora    13 年前

    您可以编写如下代码所示的break或return语句。

    字符代码='U'; 开关(代码) { 案例'N':

                    case 'U':
                        return;
                }
    

    或者,

    字符代码='u'; 开关(代码) { 案例'N':

                    case 'U':
                        break;
                }
    
        5
  •  -1
  •   alpha-mouse    15 年前

    没有问题 char . 看这个 msdn article 关于你的错误。