C# 中的 switch 语句详解与示例

发布:2024-09-12 11:31 阅读:9 点赞:0

C# 中的 switch 语句是一种控制结构,它允许基于变量的值执行不同的代码块。当需要比较一个变量与多个常量值,并根据结果执行不同的操作时,通常会使用 switch 语句。

一、基本语法

switch (expression) // 表达式
{
    case value1: // 比较值1
        // 当表达式的值等于value1时执行的代码块
        break// 结束switch语句块。如果没有break,程序将继续执行下一个case

    case value2: // 比较值2
        // 当表达式的值等于value2时执行的代码块
        break;

    case value3: // 比较值3
        // 当表达式的值等于value3时执行的代码块
        break;

    default// 可选,默认情况,当没有任何一个case匹配时执行
        // 当表达式的值不等于任何case值时执行的代码块
        break;
}

二、示例

1. 基本示例(int 类型)

// 当参数 inputValue 设置为 2 时
public void UseOfSingleWithIntTypeSwitchCase(int inputValue)
{
    switch (inputValue) // 判断 inputValue 的值
    {
        case 1// 如果 inputValue 等于 1
            Console.WriteLine("Input Value is 1"); // 输出 "Input Value is 1"
            break// 结束 switch 语句

        case 2// 如果 inputValue 等于 2
            Console.WriteLine("Input Value is 2"); // 输出 "Input Value is 2"
            break;

        case 3// 如果 inputValue 等于 3
            Console.WriteLine("Input Value is 3"); // 输出 "Input Value is 3"
            break;

        default// 如果 inputValue 不等于以上任何一个值
            Console.WriteLine("Input Value is something else"); // 输出 "Input Value is something else"
            break;
    }
}

输出将是 "Input Value is 2"。

2. 字符串示例

// 当参数 inputValue 设置为 "green" 时
public void UseOfSingleWithStringTypeSwitchCase(string inputColorValue)
{
    switch (inputColorValue) // 判断 inputColorValue 的值
    {
        case "red"// 如果 inputColorValue 等于 "red"
            Console.WriteLine("The color is red"); // 输出 "The color is red"
            break;

        case "blue"// 如果 inputColorValue 等于 "blue"
            Console.WriteLine("The color is blue"); // 输出 "The color is blue"
            break;

        case "green"// 如果 inputColorValue 等于 "green"
            Console.WriteLine("The color is green"); // 输出 "The color is green"
            break;

        default// 如果 inputColorValue 不等于以上任何一个值
            Console.WriteLine("Unknown color"); // 输出 "Unknown color"
            break;
    }
}

输出将是 "The color is green"。

3. 多个 Case 在同一块(穿透行为)

// 当参数 inputValue 设置为 'C' 时
public void UseOfMultipleSwitchCase(char inputValue)
{
    switch (inputValue) // 判断 inputValue 的值
    {
        case 'A'// 如果 inputValue 等于 'A'
        case 'B'// 或者 inputValue 等于 'B'
        case 'C'// 或者 inputValue 等于 'C'
            Console.WriteLine("You passed!"); // 输出 "You passed!"
            break;

        case 'D'// 如果 inputValue 等于 'D'
        case 'F'// 或者 inputValue 等于 'F'
            Console.WriteLine("You failed."); // 输出 "You failed."
            break;

        default// 如果 inputValue 不等于以上任何一个值
            Console.WriteLine("Invalid grade"); // 输出 "Invalid grade"
            break;
    }
}

输出将是 "You passed!"。

4. 带 when 子句的 switch(C# 7.0+)

// 当参数 inputValue 设置为 5 时
public void UseOfSingleWithWhenClauseSwitchCase(int inputValue)
{
    switch (inputValue) // 判断 inputValue 的值
    {
        case int n when (n >= 1 && n <= 10): // 如果 inputValue 在 1 和 10 之间
            Console.WriteLine("inputValue is between 1 and 10")
// 输出 "inputValue is between 1 and 10"
            break;

        case int n when (n > 10): // 如果 inputValue 大于 10
            Console.WriteLine("inputValue is greater than 10")
// 输出 "inputValue is greater than 10"
            break;

        default// 如果 inputValue 不满足以上条件
            Console.WriteLine("inputValue is less than 1"); // 输出 "inputValue is less than 1"
            break;
    }
}

输出将是 "inputValue is between 1 and 10"。

5. switch 表达式(C# 8.0+)

// 当参数 inputValue 设置为 4 时
public void UseOfSwitchExpressionCase(int inputValue)
{
    string result = inputValue switch // 判断 inputValue 的值
    {
        1 => "inputValue is one"// 如果 inputValue 等于 1
        2 => "inputValue is two"// 如果 inputValue 等于 2
        3 => "inputValue is three"// 如果 inputValue 等于 3
        _ => "inputValue is something else" // 如果 inputValue 不等于以上任何一个值
    };

    Console.WriteLine(result); // 输出 result 的值
}

输出将是 "inputValue is something else"。

6. 枚举与 switch 结合使用

// 当参数 inputValue 设置为 Operation.Add 时
public enum Operation // 定义枚举类型 Operation
{
    Add, // 加法
    Subtract, // 减法
    Multiply, // 乘法
    Divide // 除法
}

public void UseOfEnumBasedSwitchCase(int num1, int num2, Operation op)
{
    switch (op) // 判断 op 的值
    {
        case Operation.Add: // 如果 op 等于 Operation.Add
            Console.WriteLine($"Output Result is: {num1 + num2}"); // 输出两数相加的结果
            break;

        case Operation.Subtract: // 如果 op 等于 Operation.Subtract
            Console.WriteLine($"Output Result is: {num1 - num2}"); // 输出两数相减的结果
            break;

        case Operation.Multiply: // 如果 op 等于 Operation.Multiply
            Console.WriteLine($"Output Result is: {num1 * num2}"); // 输出两数相乘的结果
            break;

        case Operation.Divide: // 如果 op 等于 Operation.Divide
            if (num2 != 0// 检查除数是否为零
            {
                Console.WriteLine($"Output Result is: {num1 / num2}"); // 输出两数相除的结果
            }
            else
            {
                Console.WriteLine("Cannot divide by zero"); // 输出 "Cannot divide by zero"
            }
            break;

        default// 如果 op 不等于以上任何一个值
            Console.WriteLine("Invalid operation"); // 输出 "Invalid operation"
            break;
    }
}

输出将是 "Output Result is: 7"。

7. 带元组模式的 switch(C# 7.0 及以后版本)

// 当参数 firstName 为 "Sanjay" 且 lastName 为 "Kumar" 时
public static void UseOfSwithCaseWithTuple(string firstName, string lastName)
{
    (string firstName, string lastName) personDetail = (firstName, lastName); // 创建元组

    switch (personDetail) // 判断 personDetail 的值
    {
        case ("Sanjay""Kumar"): // 如果 firstName 为 "Sanjay" 且 lastName 为 "Kumar"
            MessageBox.Show($"Hello, {firstName} {lastName}"); // 显示消息框
            break;

        case ("Sanjay", _): // 如果 firstName 为 "Sanjay" 且 lastName 为任意值
            MessageBox.Show($"Hello, {firstName}"); // 显示消息框
            break;

        default// 如果 personDetail 不等于以上任何一个值
            MessageBox.Show("Hello, Unknown!"); // 显示消息框
            break;
    }
}

输出将是 "Hello, Sanjay Kumar"。

三、关键要素

  • Break 语句:缺少 break 语句会导致控制流继续执行下一个 case 块。除非故意为之,否则应当始终包含 break。
  • Default 情况:当没有指定的 case 与表达式匹配时作为后备方案。虽然它是可选的,但建议包含它以增强可靠性。
  • Pattern Matching 与 when 子句:允许在 case 标签中嵌入复杂的条件。
  • Switch 表达式:引入了一种更简洁和功能性的方式来管理多个条件,适用于 C# 8.0 及以后的版本。

四、推荐做法

  • 当评估多个离散值时,使用 switch 语句。
  • 除非有意为之,否则避免不必要的穿透行为。
  • 利用 when 子句中的模式匹配来处理更复杂的情况。