C# 9 模式匹配


02/12/2021 09:56:44 | China Standard Time

模式匹配允许您用清晰、简洁的语法来表达更复杂的条件,并且可以在值具有匹配形状时从值中提取信息。模式匹配为当前已使用的算法提供了更简洁的语法。在本文中,我们将介绍 C# 9 中模式匹配的新特性。


类型模式

  1. // is pattern with Type
  2. if (input is Person)
  3. ...
  4. // case pattern with Type
  5. switch (input)
  6. {
  7. case Person:
  8. ...
  9. // is pattern with tuple Type
  10. if (input is (int, string))
  11. ...

组合模式

在 C# 之前的版本中,您已经可以使用常规逻辑操作组合模式。

  1. if (person is Student || person is Teacher)
  2. ...

但是,这不适用于 switch 表达式和 switch case。C# 9 添加了组合模式使用 and 和 or 关键字的支持,同时也适用于 if 和 switch。

  1. if (person is Student or Teacher)
  2. ...
  3. decimal discount = person switch
  4. {
  5. Student or Teacher => 0.1m,
  6. _ => 0
  7. };
  8. switch (person)
  9. {
  10. case Student or Teacher:
  11. ...

and 的匹配优先级高于 or 您可以添加括号来更改优先级。

倒置模式

使用 C# 9,您可以使用关键字倒置模式。

  1. if (person is not Student)
  2. ...
  3. switch (person)
  4. {
  5. case not Student:
  6. ...

比较有趣的是 is not null 表达式,这将会检查引用是否不为空。

  1. if (person is not null)
  2. ...

关系模式

关系模式允许您将表达式与常量数值进行比较。

  1. decimal discount = age switch
  2. {
  3. <= 2 => 1,
  4. < 6 => 0.5,
  5. < 10 => 0.2
  6. };

模式内的模式

模式也可以包含其他模式。此嵌套可让您以简洁易读的方式表达复杂的条件。以下示例结合了多种类型的模式匹配。

  1. if (person is Student { Age : > 20 and < 30 })
  2. ...

AI
Conchbrain Assistant
Privacy