C# 9 模式匹配
02/12/2021 09:56:44
| China Standard Time
模式匹配允许您用清晰、简洁的语法来表达更复杂的条件,并且可以在值具有匹配形状时从值中提取信息。模式匹配为当前已使用的算法提供了更简洁的语法。在本文中,我们将介绍 C# 9 中模式匹配的新特性。
类型模式
// is pattern with Type
if (input is Person)
...
// case pattern with Type
switch (input)
{
case Person:
...
// is pattern with tuple Type
if (input is (int, string))
...
组合模式
在 C# 之前的版本中,您已经可以使用常规逻辑操作组合模式。
if (person is Student || person is Teacher)
...
但是,这不适用于 switch 表达式和 switch case。C# 9 添加了组合模式使用 and 和 or 关键字的支持,同时也适用于 if 和 switch。
if (person is Student or Teacher)
...
decimal discount = person switch
{
Student or Teacher => 0.1m,
_ => 0
};
switch (person)
{
case Student or Teacher:
...
and 的匹配优先级高于 or 您可以添加括号来更改优先级。
倒置模式
使用 C# 9,您可以使用关键字倒置模式。
if (person is not Student)
...
switch (person)
{
case not Student:
...
比较有趣的是 is not null 表达式,这将会检查引用是否不为空。
if (person is not null)
...
关系模式
关系模式允许您将表达式与常量数值进行比较。
decimal discount = age switch
{
<= 2 => 1,
< 6 => 0.5,
< 10 => 0.2
};
模式内的模式
模式也可以包含其他模式。此嵌套可让您以简洁易读的方式表达复杂的条件。以下示例结合了多种类型的模式匹配。
if (person is Student { Age : > 20 and < 30 })
...