動作確認環境:C# 9.0(.NET 5.0)
isによるパターンマッチングの概要と具体例です。
概要
isパターン | 概要 |
---|---|
型パターン | 式の型キャスト結果を変数に保持してキャスト可否を返却する。 |
定数パターン | 式が定数式を満たすか判定する。 |
varパターン | 式の結果をローカル変数に保持してtrue を返す。スコープがfor 初期化式とは異なることに注意する。 |
具体例
using System; int x = 123; int y = 0; // 型パターン Console.WriteLine(x + 1 is int t1 ? t1 : -1); // True。 Console.WriteLine(x + 1 is short t2 ? t2 : -1); // False。 Console.WriteLine(x + 1 is object t3 ? t3 : -1); // True。 // 定数パターン Console.WriteLine(x is 123); // True Console.WriteLine(x is >= 0 and <= 123); // True Console.WriteLine(x is not (>= 0 and <= 123)); // False // Console.WriteLine(x is y); // yは変数なのでコンパイルエラー // Console.WriteLine(x is >= y); // yは変数なのでコンパイルエラー // varパターン Console.WriteLine(x is var t && t == 123); // True // Console.WriteLine(x is var t && t == 123); // tは既に存在するのでコンパイルエラー Console.WriteLine(x + 1 is var s && s == 124); // True // varパターンのスコープはforの初期化式よりも広い。 // forの初期化式はfor式内部がスコープ。varパターンはif式外部のスコープ。 if (x is var u) { Console.WriteLine(u); // 123 } Console.WriteLine(u); // 123