以下に、Switch文の使い方といくつかのコード例を紹介します。
- 基本的なSwitch文の例:
int number = 3;
switch (number)
{
case 1:
Console.WriteLine("Number is 1");
break;
case 2:
Console.WriteLine("Number is 2");
break;
case 3:
Console.WriteLine("Number is 3");
break;
default:
Console.WriteLine("Number is not 1, 2, or 3");
break;
}
- 文字列を評価するSwitch文の例:
string fruit = "apple";
switch (fruit)
{
case "apple":
Console.WriteLine("It's an apple");
break;
case "banana":
Console.WriteLine("It's a banana");
break;
case "orange":
Console.WriteLine("It's an orange");
break;
default:
Console.WriteLine("It's a fruit");
break;
}
- 列挙型を評価するSwitch文の例:
enum DayOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
DayOfWeek day = DayOfWeek.Saturday;
switch (day)
{
case DayOfWeek.Monday:
Console.WriteLine("It's Monday");
break;
case DayOfWeek.Tuesday:
Console.WriteLine("It's Tuesday");
break;
case DayOfWeek.Wednesday:
Console.WriteLine("It's Wednesday");
break;
case DayOfWeek.Thursday:
Console.WriteLine("It's Thursday");
break;
case DayOfWeek.Friday:
Console.WriteLine("It's Friday");
break;
case DayOfWeek.Saturday:
Console.WriteLine("It's Saturday");
break;
case DayOfWeek.Sunday:
Console.WriteLine("It's Sunday");
break;
}
これらの例では、Switch文を使用して条件に基づいて異なるコードブロックを実行する方法を示しています。必要に応じて、追加のケースや条件を追加することもできます。