switch 運算式:使用 switch 關鍵字模式比對運算式

您可以使用 switch 運算式,根據與輸入運算式的模式比對,從候選運算式清單中評估單一運算式。 如需 switch 陳述式內容中支援 switch 類似語意的語句相關資訊,請參閱 Selection 陳述式一文的switch 陳述式一節。

下列範例示範 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 運算式 arms,以逗號分隔。 每個 switch 運算式 arm 包含模式、選擇性案例成立條件=>權杖和運算式

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

  • 常數模式:處理 Direction 列舉定義的值。
  • 捨棄模式:處理沒有 Direction 列舉對應成員的任何整數值 (例如,(Direction)10)。 這會讓 switch 運算式完整

重要

如需 switch 運算式所支援的模式和更多範例的相關資訊,請參閱 [模式]

switch 運算式的結果是第一個 switch 運算式 arm 的運算式值,其模式符合輸入運算式,而且如果案例成立條件存在的話,則會評估為 trueswitch 運算式 arms 會以文字順序進行評估。

無法選擇較低的 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運算式

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

提示

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

C# 語言規格

如需詳細資訊,請參閱功能提案附註switch 運算式一節。

另請參閱