Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c# - switch语句中有多种情况(Multiple cases in switch statement)

Is there a way to fall through multiple case statements without stating case value: repeatedly?

(有没有一种方法可以遍历多个case语句而不声明case value:重复?)

I know this works:

(我知道这可行:)

switch (value)
{
   case 1:
   case 2:
   case 3:
      //do some stuff
      break;
   case 4:
   case 5:
   case 6:
      //do some different stuff
      break;
   default:
       //default stuff
      break;
}

but I'd like to do something like this:

(但我想做这样的事情:)

switch (value)
{
   case 1,2,3:
      //Do Something
      break;
   case 4,5,6:
      //Do Something
      break;
   default:
      //Do the Default
      break;
}

Is this syntax I'm thinking of from a different language, or am I missing something?

(我是从其他语言考虑使用这种语法吗?还是我错过了某些内容?)

  ask by theo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess this has been already answered.

(我想这已经被回答了。)

However, I think that you can still mix both options in a syntactically better way by doing:

(但是,我认为您仍然可以通过以下方法以语法上更好的方式混合使用这两个选项:)

switch (value)
{
case 1: case 2: case 3:          
    // Do Something
    break;
case 4: case 5: case 6: 
    // Do Something
    break;
default:
    // Do Something
    break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...