我想用switch,但我有很多情况,有没有捷径?到目前为止,我所知道和尝试的唯一解决方案是:
switch (number)
{
case 1: something; break;
case 2: other thing; break;
...
case 9: .........; break;
}
Run Code Online (Sandbox Code Playgroud)
我希望我能做的是:
switch (number)
{
case (1 to 4): do the same for all of them; break;
case (5 to 9): again, same thing for these numbers; break;
}
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!
我只是回顾一些旧的代码(有一些空闲时间),我注意到一个相当冗长的switch语句.由于获得了新知识,我已经以下面的形式重构了它:
private Dictionary<string, Action> createView
{
get
{
return new Dictionary<string, Action>()
{
{"Standard", CreateStudySummaryView},
{"By Group", CreateStudySummaryByGroupView},
{"By Group/Time", CreateViewGroupByHour}
};
}
}
Run Code Online (Sandbox Code Playgroud)
你会考虑这个好习惯,还是仅仅是一个超级丰富和不必要的案例?我渴望确保我学到的新技术,仅仅为了它而不是聪明,并且它们实际上为代码增加了好处.
谢谢.
可能重复:
Switch中的多个案例:
是否可以执行多个常量表达式切换语句
switch (i) {
case "run","notrun", "runfaster": //Something like this.
DoRun();
break;
case "save":
DoSave();
break;
default:
InvalidCommand(command);
break;
}
Run Code Online (Sandbox Code Playgroud) 有谁知道是否可以在switch语句中包含一个范围(如果是,如何)?
例如:
switch (x)
{
case 1:
//do something
break;
case 2..8:
//do something else
break;
default:
break;
}
Run Code Online (Sandbox Code Playgroud)
编译器似乎不喜欢这种语法 - 它也不喜欢:
case <= 8:
Run Code Online (Sandbox Code Playgroud) 在C#中,switch语句不允许案例跨越值范围.我不喜欢为此目的使用if-else循环的想法,所以有没有其他方法来检查C#中的数值范围?
我想问一个在C#中比我有更强技能的人.
是否可以减少以下代码
if(val > 20 && val < 40 )
...
else
if(val > 40 && val < 72 )
...
else
if(val > 72 && val < 88 )
...
else
...
Run Code Online (Sandbox Code Playgroud)
我们假设我有10-11个if-else语句.
缩短上述代码的最佳方法是什么?
我想像between在sql 中的东西.
如何为开关盒C#使用多个常量?从概念上讲,我正在寻找这样的东西:
switch(n)
{
case 1,2,3: //????
case 4:
default:
}
Run Code Online (Sandbox Code Playgroud) 如何在一个内部处理多个值case?所以,如果我想执行的值相同的动作"first option"和"second option"?
这是正确的方法吗?
switch(text)
{
case "first option":
{
}
case "second option":
{
string a="first or Second";
break;
}
}
Run Code Online (Sandbox Code Playgroud) 我知道这段代码不能用作"预期".只是快速查看此代码,我们认为返回值应为1,但在执行时它返回3.
// incorrect
variable = 1;
switch (variable)
{
case 1, 2:
return 1;
case 3, 4:
return 2;
default:
return 3;
}
Run Code Online (Sandbox Code Playgroud)
并且有一些正确的选项可以做到这一点:
// correct 1
variable = 1;
switch (variable)
{
case 1: case 2:
return 1;
case 3: case 4:
return 2;
default:
return 3;
}
Run Code Online (Sandbox Code Playgroud)
要么
// correct 2
switch (variable)
{
case 1:
case 2:
return 1;
case 3:
case 4:
return 2;
default:
return 3;
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么不正确的表单编译没有错误甚至警告(至少在Borland C++编译器中).
编译器在该代码中理解什么?
如何&&在开关盒中使用操作器?
这就是我想要做的:
private int retValue()
{
string x, y;
switch (x && y)
{
case "abc" && "1":
return 10;
break;
case "xyz" && "2":
return 20;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,"abc"并且"1"都是类型string,编译器给我的消息:
"operator &&不能应用于字符串"