is 運算子 在執行期檢查運算式結果是否可透過參考轉換、裝箱、拆箱轉換為指定型別,回傳 bool。
expr is Type // 回傳 bool
// 真 當 expr ≠ null 且 expr 的執行期型別可隱含/顯式參考轉換為 Type
// 或 expr 為實值型別且可裝箱/拆箱為 Type
Console.WriteLine(1 is int); // True
Console.WriteLine(1 is float); // False (int 不能隱含參考轉換為 float)
Console.WriteLine(1.0 is float); // False (double 不能隱含參考轉換為 float)
Console.WriteLine(1.0 is double); // True
if (obj is int i) { Console.WriteLine(i * 2); } // 宣告區域變數
if (obj is string { Length: > 10 } s) { ... } // 屬性模式 (C# 8+)
is 不考慮使用者定義轉換運算子,僅看 CLI 內建轉換。null is T 永遠為 false(任何 T)。null,但 Nullable<T> 可能為 null。is + 強制轉型 兩次型別檢查;優先使用 as + null 檢查或型別模式 is T v 合併為單次檢查。