is 運算子 (C# 參考)
is
運算子會檢查運算式的結果是否與指定的類型相容。 如需類型測試 is
運算子的相關資訊,請參閱 Type-testing 和 cast 運算子一文的 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 運算子 一節。
另請參閱
意見反應
提交並檢視相關的意見反應