版本
从 C# 7.0
开始
使用方法
类型模式
- 描述:用于测试表达式是否可转换为指定类型,如果可以,则将其转换为该类型的一个变量。
- 格式:
expr is type varname
,varname
是类型匹配后,赋值的变量名称。 - 例子:
using System; public class Employee : IComparable { public String Name { get; set; } public int Id { get; set; } public int CompareTo(Object o) { if (o is Employee e) { return Name.CompareTo(e.Name); } throw new ArgumentException("o is not an Employee object."); } }
常量模式
- 描述:用于测试表达式计算结果是否为指定的常数值。
- 格式:
expr is constant
,constant
的可以是下面的表达式:- 文字值。
- 一个枚举常量。
- 已声明
const
变量的名称。
- 例子:
using System; public class Dice { Random rnd = new Random(); public Dice() { } public int Roll() { return rnd.Next(1, 7); } } class Program { static void Main(string[] args) { var d1 = new Dice(); ShowValue(d1); } private static void ShowValue(object o) { const int HIGH_ROLL = 6; if (o is Dice d && d.Roll() is HIGH_ROLL) Console.WriteLine($"The value is {HIGH_ROLL}!"); else Console.WriteLine($"The dice roll is not a {HIGH_ROLL}!"); } }
- 可以执行
null
检查:expr is null
var 模式
- 描述:始终匹配成功,可将表达式的值绑定到新局部变量。
- 格式:
expr is var varname
- 如果
expr
为null
,is
表达式也为true
,varname
为null
。 - 示例:
这里作为临时变量。using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] testSet = { 100271, 234335, 342439, 999683 }; var primes = testSet.Where(n => Factor(n).ToList() is var factors && factors.Count == 2 && factors.Contains(1) && factors.Contains(n)); foreach (int prime in primes) { Console.WriteLine($"Found prime: {prime}"); } } static IEnumerable<int> Factor(int number) { int max = (int)Math.Sqrt(number); for (int i = 1; i <= max; i++) { if (number % i == 0) { yield return i; if (i != number / i) { yield return number / i; } } } } } // The example displays the following output: // Found prime: 100271 // Found prime: 999683
[1] is 的用法