在C#中switch语句fallthrough? [英] Switch statement fallthrough in C#?

查看:322
本文介绍了在C#中switch语句fallthrough?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

switch语句fallthrough是为爱开关我个人的一个重要原因,如果/否则,如果结构。一个例子是为了在这里:

Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:

static string NumberToWords(int number)
{
    string[] numbers = new string[] 
        { "", "one", "two", "three", "four", "five", 
          "six", "seven", "eight", "nine" };
    string[] tens = new string[] 
        { "", "", "twenty", "thirty", "forty", "fifty", 
          "sixty", "seventy", "eighty", "ninety" };
    string[] teens = new string[]
        { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
          "sixteen", "seventeen", "eighteen", "nineteen" };

    string ans = "";
    switch (number.ToString().Length)
    {
        case 3:
            ans += string.Format("{0} hundred and ", numbers[number / 100]);
        case 2:
            int t = (number / 10) % 10;
            if (t == 1)
            {
                ans += teens[number % 10];
                break;
            }
            else if (t > 1)
                ans += string.Format("{0}-", tens[t]);
        case 1:
            int o = number % 10;
            ans += numbers[o];

            break;
        default:
            throw new ArgumentException("number");
    }
    return ans;
}

聪明人畏缩,因为的String [] s需要的功能外声明:嗯,他们是,这仅仅是一个例子。

The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.

编译器失败,出现以下错误:

The compiler fails with the following error:


Control cannot fall through from one case label ('case 3:') to another
Control cannot fall through from one case label ('case 2:') to another

为什么呢? ,是有什么办法让这种行为不具有三个如果 S'

推荐答案

我在别处提供的答案)

开关下降 - 情况 s时,可以通过在一个<$ C无code实现$ C>情况(见 0的情况),或使用特殊的的goto case (看案例1 )或转到默认(见案例2 )形式:

Falling through switch-cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms:

switch (/*...*/) {
    case 0: // shares the exact same code as case 1
    case 1:
        // do something
        goto case 2;
    case 2:
        // do something else
        goto default;
    default:
        // do something entirely different
        break;
}

这篇关于在C#中switch语句fallthrough?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆