switch(code)
{
case 'A':
case 'a':
// to do
default:
// to do
}有没有办法将这两个"case“语句合并在一起?
发布于 2014-01-31 04:02:25
您只需要为当前代码使用break;,如下所示:
switch (code)
{
case 'A':
case 'a':
break;
// to do
default:
// to do
break;
}但是,如果要比较大写和小写字符,则可以使用char.ToUpperInvariant,然后仅指定大写字符的大小写:
switch (char.ToUpperInvariant(code))
{
case 'A':
break;
// to do
default:
// to do
break;
}发布于 2014-01-31 04:05:34
http://msdn.microsoft.com/en-us/library/06tc147t.aspx
class Program
{
static void Main(string[] args)
{
int switchExpression = 3;
switch (switchExpression)
{
// A switch section can have more than one case label.
case 0:
case 1:
Console.WriteLine("Case 0 or 1");
// Most switch sections contain a jump statement, such as
// a break, goto, or return. The end of the statement list
// must be unreachable.
break;
case 2:
Console.WriteLine("Case 2");
break;
// The following line causes a warning.
Console.WriteLine("Unreachable code");
// 7 - 4 in the following line evaluates to 3.
case 7 - 4:
Console.WriteLine("Case 3");
break;
// If the value of switchExpression is not 0, 1, 2, or 3, the
// default case is executed.
default:
Console.WriteLine("Default case (optional)");
// You cannot "fall through" any switch section, including
// the last one.
break;
}
}
}发布于 2014-01-31 04:12:16
Switch将对满足的每个条件进行求值,直到达到break、default或最终结束括号。
也就是说,它将执行任何匹配的case语句,直到它命中这些指令之一。
对所有等价的cases进行分组,并在最后一个break之后添加一个all以合并它们。
请注意,如果没有匹配项,它将落入default块。
https://stackoverflow.com/questions/21466321
复制相似问题