C# 9 增强的模式匹配

C# 9 中进一步增强了模式匹配的用法,使得模式匹配更为强大

增加了 and/or/not 操作符,而且可以直接判断属性

IF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var person = new Person();

// or
// string.IsNullOrEmpty(person.Description)
if (person.Description is null or { Length: 0 })
{
Console.WriteLine($"{nameof(person.Description)} is IsNullOrEmpty");
}

// and
// !string.IsNullOrEmpty(person.Name)
if (person.Name is not null and { Length: > 0 })
{
if (person.Name[0] is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '.')
{

}
}

// not
if (person.Name is not null)
{

}

Switch

这不仅适用于 is 也可以在 switch 中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
switch (person.Age)
{
case >= 0 and <= 3:
Console.WriteLine("baby");
break;

case > 3 and < 14:
Console.WriteLine("child");
break;

case > 14 and < 22:
Console.WriteLine("youth");
break;

case > 22 and < 60:
Console.WriteLine("Adult");
break;

case >= 60 and <= 500:
Console.WriteLine("Old man");
break;

case > 500:
Console.WriteLine("monster");
break;
}