为什么SWITCH ... CASE没有服用'char'?

时间:2010-11-25 17:04:25

标签: c#

我对此代码有两个问题:

public int InsertOrUpdateRecord(char _code, string _databaseFileName)
{

   switch(_code)
   {
      case 'N':
           // Some code here

       case 'U':
           // Some code here
   }
       return 0;
}
  1. 它不接受 char 单引号和双引号值。
  2. 如果我将_code作为字符串传递,则会在 case 中显示红色下划线并显示以下错误:
  3. 控件不能通过一个案例标签落入另一个案例标签。

5 个答案:

答案 0 :(得分:13)

编译错误的原因是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
}

答案 1 :(得分:2)

您需要在案例结尾处执行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;
}

答案 2 :(得分:0)

除非你想在任何一种情况下都这样做:

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指令。

答案 3 :(得分:0)

您可以编写一个break或return语句,如下面的代码。

char _code ='U';                 开关(_code)                 {                     案例'N':

                case 'U':
                    return;
            }

OR,

char _code ='u';                 开关(_code)                 {                     案例'N':

                case 'U':
                    break;
            }

答案 4 :(得分:-1)

char没有问题。有关您的错误,请参阅此msdn article

相关问题