is 運算子 (C# 參考)

is 運算子會檢查運算式結果的執行階段型別是否與指定型別相容。 如需型別測試 is 運算子的相關資訊,請參閱型別測試和轉換運算子一文的 is 運算子小節。 您也可以使用 is 運算子來對應運算式與模式,如下列範例所示:

static bool IsFirstFridayOfOctober(DateTime date) =>
    date is { Month: 10, Day: <=7, DayOfWeek: DayOfWeek.Friday };

在上述範例中,is 運算子會以巢狀常數關係模式對應屬性模式的運算式。

is 運算子在下列案例中很有用:

  • 若要檢查運算式的執行階段類型,如下列範例所示:

    int i = 34;
    object iBoxed = i;
    int? jNullable = 42;
    if (iBoxed is int a && jNullable is int b)
    {
        Console.WriteLine(a + b);  // output 76
    }
    

    上述範例顯示宣告模式的使用方式。

  • 檢查 null 如下列範例所示:

    if (input is null)
    {
        return;
    }
    

    當您對應運算式與 null 時,編譯器會保證不會叫用任何使用者多載 ==!= 運算子。

  • 您可以如下列範例所示,使用否定模式來執行非 Null 檢查:

    if (result is not null)
    {
        Console.WriteLine(result.ToString());
    }
    
  • 從 C# 11 開始,您可以使用清單模式來對應清單或陣列的項目。 下列程式碼會檢查陣列中是否有預期位置的整數值:

    int[] empty = [];
    int[] one = [1];
    int[] odd = [1, 3, 5];
    int[] even = [2, 4, 6];
    int[] fib = [1, 1, 2, 3, 5];
    
    Console.WriteLine(odd is [1, _, 2, ..]);   // false
    Console.WriteLine(fib is [1, _, 2, ..]);   // true
    Console.WriteLine(fib is [_, 1, 2, 3, ..]);     // true
    Console.WriteLine(fib is [.., 1, 2, 3, _ ]);     // true
    Console.WriteLine(even is [2, _, 6]);     // true
    Console.WriteLine(even is [2, .., 6]);    // true
    Console.WriteLine(odd is [.., 3, 5]); // true
    Console.WriteLine(even is [.., 3, 5]); // false
    Console.WriteLine(fib is [.., 3, 5]); // true
    

注意

如需 is 運算子所支援的模式完整清單,請參閱模式

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格模式比對is 運算子一節。

另請參閱