运算符 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 模式的完整列表,请参阅 Patterns

C# 语言规范

有关详细信息,请参阅 C# 语言规范模式匹配is 运算符部分。

另请参阅