C# 9 新特性 —— 增强的模式匹配
C# 9 新特性 —— 增强的模式匹配
Intro#
C# 9 中进一步增强了模式匹配的用法,使得模式匹配更为强大,我们一起来了解一下吧
Sample#
C# 9 中增强了模式匹配的用法,增加了 and
/or
/not
操作符,而且可以直接判断属性,来看一下下面的这个示例:
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)
{
}
这里的代码使用 DnSpy
反编译之后的代码是下面这样的:
Person person = new Person();
string text = person.Description;
bool flag = text == null || text.Length == 0;
if (flag)
{
Console.WriteLine("Description is IsNullOrEmpty");
}
text = person.Name;
bool flag2 = text != null && text.Length > 0;
if (flag2)
{
char c = person.Name[0];
if (c >= 'a')
{
if (c > 'z')
{
goto IL_8B;
}
}
else if (c >= 'A')
{
if (c > 'Z')
{
goto IL_8B;
}
}
else if (c != ',' && c != '.')
{
goto IL_8B;
}
bool flag3 = true;
goto IL_8E;
IL_8B:
flag3 = false;
IL_8E:
bool flag4 = flag3;
if (flag4)
{
}
}
bool flag5 = person.Name != null;
if (flag5)
{
}
Switch#
这不仅适用于 is
也可以在 switch
中使用
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;
}
反编译后的代码:
int age = person.Age;
int num = age;
if (num < 22)
{
if (num < 14)
{
if (num >= 0)
{
if (num > 3)
{
Console.WriteLine("child");
}
else
{
Console.WriteLine("baby");
}
}
}
else if (num > 14)
{
Console.WriteLine("youth");
}
}
else if (num < 60)
{
if (num > 22)
{
Console.WriteLine("Adult");
}
}
else if (num > 500)
{
Console.WriteLine("monster");
}
else
{
Console.WriteLine("Old man");
}
More#
可以看到有些情况下可以简化不少代码,尤其是 if
分支比较多的情况下使用上面 switch
这样的写法会清晰很多
但是如果只是 string.IsNullOrEmpty
这种代码最好还是不要写得这么骚了,小心要被同事吐槽了
炫技需谨慎,小心被 ...
Reference#
作者:weihanli
出处:https://www.cnblogs.com/weihanli/p/14226240.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?