is 运算符检查表达式的结果是否与给定的类型相匹配。 有关类型测试 is 运算符的信息,请参阅文章 类型测试和强制转换运算符 is 运算符 部分。 还可使用 is 运算符将表达式与模式相匹配,如下例所示:

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

在前面的示例中, is 运算符将表达式与带有嵌套 常量 关系 (在 C# 9.0 和更高版本中可用)模式的 属性模式 相匹配。

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 匹配时,编译器保证不会调用用户重载的 == != 运算符。

  • 从 C# 9.0 开始,可使用 否定模式 执行非 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
  •