C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# switch

C# switch

C# switch 语句 根据多个条件执行一个语句。类似于 C# 中的 if-else-if 梯形语句。
语法:
switch(expression){  
case value1:  
 //code to be executed; 
 break;
case value2:  
 //code to be executed;  
 break;
......  
  
default:   
 //code to be executed if all cases are not matched;  
 break;
}  
C# switch 语句流

C# switch 示例

using System;
  public class SwitchExample
    {
      public static void Main(string[] args)
      {
          Console.WriteLine("Enter a number:");
          int num = Convert.ToInt32(Console.ReadLine());
          switch (num)
          {
              case 10: Console.WriteLine("It is 10"); break;
              case 20: Console.WriteLine("It is 20"); break;
              case 30: Console.WriteLine("It is 30"); break;
              default: Console.WriteLine("Not 10, 20 or 30"); break;
          }
      }
    }
输出:
Enter a number:
10
It is 10
输出:
Enter a number:
55
Not 10, 20 or 30
注意: 在 C# 中,break 语句在 switch case 中是必须的。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4