C # 9.0 的模式匹配
void M(object o1, object o2) { var t = (o1, o2); if (t is (int, string)) {} // test if o1 is an int and o2 is a string switch (o1) { case int: break; // test if o1 is an int case System.String: break; // test if o1 is a string } }
关系模式 与常数值相比,关系模式允许程序员表达输入值必须满足关系约束:
public static LifeStage LifeStageAtAge(int age) => age switch { < 0 => LifeStage.Prenatal, < 2 => LifeStage.Infant, < 4 => LifeStage.Toddler, < 6 => LifeStage.EarlyChild, < 12 => LifeStage.MiddleChild, < 20 => LifeStage.Adolescent, < 40 => LifeStage.EarlyAdult, < 65 => LifeStage.MiddleAdult, _ => LifeStage.LateAdult, };
关系模式支持 < 所有内置类型上的关系运算符<= 和, > >= 它们支持在表达式中 使用两个具有相同类型的操作数的内置类型。 具体而言,支持sbyte byte short ushort 、 int 、 uint 、 long ulong char float double decimal nint nuint 和的所有关系模式。
模式组合器
if (e is not null) ... bool IsLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z'; bool IsLetter(char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z');
语义 (例如,类型) 关系运算符
bool IsValidPercentage(int x) => x is >= 0 and <= 100; bool IsValidPercentage(object x) => x is >= 0 and <= 100; bool IsValidPercentage(object x) => x is >= 0 and <= 100 or // integer tests >= 0F and <= 100F or // float tests >= 0D and <= 100D; // double tests
从左侧的左侧流向类型信息 and
bool isSmallByte(object o) => o is byte and < 100;
byte b = ...; int x = b switch { <100 => 0, 100 => 1, 101 => 2, >101 => 3 };