共用方式為


switch 運算式 - 使用 關鍵詞的模式比對 switch 表示式

您可以使用 switch 表達式,根據模式比對與輸入表達式,從候選表達式清單中評估單一表達式。 如需語句內容中支持switch類似語意的語句資訊switch,請參閱 switchSelection 語句一文的 語句一節。

下列範例示範 switch 表達式,其會將在線地圖中表示視覺方向的值 enum 轉換為對應的基數方向:

public static class SwitchExample
{
    public enum Direction
    {
        Up,
        Down,
        Right,
        Left
    }

    public enum Orientation
    {
        North,
        South,
        East,
        West
    }

    public static Orientation ToOrientation(Direction direction) => direction switch
    {
        Direction.Up    => Orientation.North,
        Direction.Right => Orientation.East,
        Direction.Down  => Orientation.South,
        Direction.Left  => Orientation.West,
        _ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"),
    };

    public static void Main()
    {
        var direction = Direction.Right;
        Console.WriteLine($"Map view direction is {direction}");
        Console.WriteLine($"Cardinal orientation is {ToOrientation(direction)}");
        // Output:
        // Map view direction is Right
        // Cardinal orientation is East
    }
}

上述範例顯示表示式的基本元素 switch

  • 後面接著 關鍵詞的 switch 表達式。 在上述範例中,它是 direction 方法參數。
  • 表達式switch,以逗號分隔。 每個 switch 運算式arm都包含 模式、選擇性 大小寫防護=> 令牌和 表達式

在上述範例中, switch 表達式會使用下列模式:

  • 常數模式:處理列舉定義的Direction值。
  • 捨棄模式:處理任何沒有列舉之對應成員的Direction整數值(例如 , (Direction)10switch這使得表達式詳盡無遺

這很重要

如需表達式所支援的 switch 模式和更多範例的相關信息,請參閱 模式

運算式的結果是第一switchswitch表達式arm的運算式值,其模式符合輸入運算式,如果存在,則其案例防護會評估為 true。 表達式 switch 臂會以文字順序進行評估。

當無法選擇較低的 switch 表達式arm時,編譯程式會產生錯誤,因為較高的 switch 表達式arm符合其所有值。

案例防護

模式可能不夠表達,無法指定評估arm表達式的條件。 在這種情況下,您可以使用 案例防護案例防護是必須與相符模式一起滿足的另一個條件。 案例防護必須是布爾表達式。 您可以在遵循模式的 when 關鍵詞後面指定案例防護,如下列範例所示:

public readonly struct Point
{
    public Point(int x, int y) => (X, Y) = (x, y);
    
    public int X { get; }
    public int Y { get; }
}

static Point Transform(Point point) => point switch
{
    { X: 0, Y: 0 }                    => new Point(0, 0),
    { X: var x, Y: var y } when x < y => new Point(x + y, y),
    { X: var x, Y: var y } when x > y => new Point(x - y, y),
    { X: var x, Y: var y }            => new Point(2 * x, 2 * y),
};

上述範例會使用具有巢狀 var 模式的屬性模式

非詳盡的切換表達式

如果表達式的模式都 switch 不符合輸入值,運行時間就會擲回例外狀況。 在 .NET Core 3.0 和更新版本中,例外狀況是 System.Runtime.CompilerServices.SwitchExpressionException。 在 .NET Framework 中,例外狀況是 InvalidOperationException。 在大部分情況下,如果 switch 表達式未處理所有可能的輸入值,編譯程式會產生警告。 未處理所有可能輸入時,清單模式不會產生警告。

小提示

若要保證 switch 表達式會處理所有可能的輸入值,請提供 switch 具有 捨棄模式的運算式臂。

C# 語言規格

如需詳細資訊,請參閱 switchC# 語言規格的運算式區段。

另請參閱