switch文でOR条件を表現したい時は、
case 条件1:
case 条件2:
のように続けて書くことで実現できる。
1 2 3 4 5 6 7 8 9 10 11 |
string str = "a"; switch (str) { case "a": case "b": Console.WriteLine("aかbです。"); break; default: Console.WriteLine("aでもbでもないです。"); break; } |
ただし、以下のような記述は不可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int rank = 3; switch (rank) { case 3: Console.WriteLine("大変良いです。"); //「3」の時に実行 case 2: Console.WriteLine("合格です。"); //「2」または「3」の時に実行 break; case 1: Console.WriteLine("不合格です。"); break; default: break; } |
一つのラベルには必ずそれに対応するbreak文が無いといけない。