Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# Switch 语句


C# Switch 语句

使用 switch 语句选择要执行的多个代码块之一。

语法

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

它是这样工作的

  • switch 表达式会被评估一次
  • 表达式的值与每个 case 的值进行比较
  • 如果匹配,则执行关联的代码块
  • 本章稍后将介绍 breakdefault 关键字

下面的示例使用星期几的数字来计算星期几的名称

示例

int day = 4;
switch (day) 
{
  case 1:
    Console.WriteLine("Monday");
    break;
  case 2:
    Console.WriteLine("Tuesday");
    break;
  case 3:
    Console.WriteLine("Wednesday");
    break;
  case 4:
    Console.WriteLine("Thursday");
    break;
  case 5:
    Console.WriteLine("Friday");
    break;
  case 6:
    Console.WriteLine("Saturday");
    break;
  case 7:
    Console.WriteLine("Sunday");
    break;
}
// Outputs "Thursday" (day 4)

自己尝试 »


Break 关键字

当 C# 遇到 break 关键字时,它会跳出 switch 代码块。

这将停止执行块内的更多代码和 case 测试。

当找到匹配项并且工作完成时,该是 break 的时候了。无需进行更多测试。

break 可以节省大量执行时间,因为它“忽略”了 switch 代码块中所有其余代码的执行。



Default 关键字

default 关键字是可选的,它指定如果没有任何 case 匹配则要运行的某些代码

示例

int day = 4;
switch (day) 
{
  case 6:
    Console.WriteLine("Today is Saturday.");
    break;
  case 7:
    Console.WriteLine("Today is Sunday.");
    break;
  default:
    Console.WriteLine("Looking forward to the Weekend.");
    break;
}
// Outputs "Looking forward to the Weekend."

自己尝试 »


C# 练习

通过练习测试自己

练习

插入缺失的部分以完成以下 switch 语句。

int day = 2;
switch () 
{
   1:
    Console.WriteLine("Monday");
    break;
   2:
    Console.WriteLine("Tuesday");
    ;
}

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.