Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีเขียน Switch Expression ใหม่ใน C# 8.0

Switch Expression ให้ Switch-like Semantics ใน Expression Context

Switch Statement เป็น Selection Statement ที่เลือก Switch Section เดียวจาก List ของ Candidates ตาม Pattern Match กับ Match Expression

Switch Statement บ่อยครั้งใช้แทน If-Else Construct ถ้า Single Expression ถูก Test กับ 3+ Conditions

Syntax ใหม่: Switch Expression (Expression-bodied)


// เก่า: Switch Statement
string message;
switch (fruit) {
    case "Apple": message = "Red"; break;
    case "Banana": message = "Yellow"; break;
    default: message = "Unknown"; break;
}

// ใหม่: Switch Expression (C# 8.0)
var message = fruit switch {
    "Apple" => "Red",
    "Banana" => "Yellow",
    _ => "Unknown"
};

ตัวอย่างครบถ้วน


class Program {
    public enum Fruits { Red, Green, Blue }
    
    public static void Main() {
        Fruits c = (Fruits)(new Random()).Next(0, 3);
        
        // เก่า: Switch Statement
        switch (c) {
            case Fruits.Red:
                Console.WriteLine("The fruit is red");
                break;
            case Fruits.Green:
                Console.WriteLine("The fruit is green");
                break;
            case Fruits.Blue:
                Console.WriteLine("The fruit is blue");
                break;
            default:
                Console.WriteLine("The fruit is unknown.");
                break;
        }
        
        // ใหม่: Switch Expression
        var message = c switch {
            Fruits.Red => "The fruit is red",
            Fruits.Green => "The fruit is green",
            Fruits.Blue => "The fruit is blue",
            _ => "The fruit is unknown"
        };
        
        Console.WriteLine(message);
        Console.ReadLine();
    }
}

Output


The fruit is green
The fruit is green

Pattern Matching ใน Switch Expressions

1. Type Pattern


public static string Describe(object obj) => obj switch {
    int i => $"Integer: {i}",
    string s => $"String: {s.Length} chars",
    double d => $"Double: {d:F2}",
    null => "Null",
    _ => "Unknown type"
};

2. Property Pattern


public static string GetStatus(User user) => user switch {
    { IsActive: true, Role: "Admin" } => "Active Admin",
    { IsActive: true, Role: "User" } => "Active User",
    { IsActive: false } => "Inactive",
    null => "No User",
    _ => "Unknown"
};

3. Tuple Pattern


public static string RockPaperScissors(string player1, string player2) => (player1, player2) switch {
    ("Rock", "Scissors") => "Player 1 Wins",
    ("Scissors", "Paper") => "Player 1 Wins",
    ("Paper", "Rock") => "Player 1 Wins",
    (_, _) when player1 == player2 => "Draw",
    _ => "Player 2 Wins"
};

4. Relational Patterns (C# 9.0+)


public static string Grade(int score) => score switch {
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

5. Logical Patterns (C# 9.0+)


public static string Check(int x) => x switch {
    > 0 and < 100 => "In Range",
    < 0 or > 100 => "Out of Range",
    0 => "Zero",
    _ => "Invalid"
};

Switch Expression vs Switch Statement

AspectSwitch StatementSwitch Expression
Returns Valueไม่ (ต้อง Assign เอง)ใช่ (เป็น Expression)
Fall-throughได้ (ต้อง break)ไม่มี (Pattern Matching)
SyntaxVerboseConcise, Functional
Pattern MatchingLimited (C# 7+)Full Support
Discard (_)default:_ =>
When Clausecase int x when x > 0:int x when x > 0 =>

ข้อควรระวัง

  • Switch Expression ต้อง Exhaustive (Crush ทุก Cases) มิฉะนั้น Compile Warning
  • ใช้ _ (Discard) แทน default
  • ไม่มี break เพราะไม่มี Fall-through
  • แต่ละ Arm ต้องเป็น Expression (Single Statement) ไม่ใช่ Block