在C#中,您可以使用switch
语句来处理多个条件。switch
语句允许您根据不同的条件执行不同的代码块。当条件匹配时,将执行相应的case
标签中的代码。如果没有匹配的条件,则执行default
标签中的代码(如果提供了default
标签)。
以下是一个处理多个条件的switch
语句示例:
using System; class Program { static void Main() { int number = 2; string day = "Wednesday"; 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 (day) { case "Monday": Console.WriteLine("Day is Monday."); break; case "Tuesday": Console.WriteLine("Day is Tuesday."); break; case "Wednesday": Console.WriteLine("Day is Wednesday."); break; case "Thursday": Console.WriteLine("Day is Thursday."); break; case "Friday": Console.WriteLine("Day is Friday."); break; case "Saturday": Console.WriteLine("Day is Saturday."); break; case "Sunday": Console.WriteLine("Day is Sunday."); break; default: Console.WriteLine("Day is not Monday through Sunday."); break; } } }
在这个示例中,我们有两个switch
语句。第一个switch
语句处理整数number
,第二个switch
语句处理字符串day
。在每个switch
语句中,我们为每个可能的值定义了一个case
标签,并为每个case
标签提供了相应的代码块。如果没有匹配的条件,则执行default
标签中的代码。