switch(code)
{
case 'A':
case 'a':
// to do
default:
// to do
}
有没有什么方法可以将两个“case”语句合并在一起?
您只需要像这样在您现有的代码中使用 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;
}
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;
}
}
}
Switch
会对每个满足条件的情况进行评估,直到遇到 break
、default
或最终的闭合括号。
也就是说,它将执行任何匹配的 case
语句,直到遇到这些指令之一。
将所有等效的 cases
分组,并在最后添加一个 break
来合并它们。
请注意,如果没有匹配项,它将进入 default
块。
default
,然后是 case
语句,那么 case
语句将不会被执行吗? - Thomas Matthews
switch(code.ToUpper())
怎么样,然后每个case
都使用大写? - Prixchar.ToUpperInvariant
,这比char.ToUpper
更好。 - Habib