2020-11-06

使用 C# 9.0 新语法提升 if 语句美感

C# 语言一贯秉承简洁优美的宗旨,每次升级都会带来一些语法糖,让我们可以使代码变得更简洁。本文分享两个使用 C# 9.0 提升 if 语句美感的技巧示例。

使用属性模式代替 IsNullOrEmpty

在任何你使用 IsNullOrEmpty 的时候,可以考虑这样替换:

string? hello = "hello world";hello = null;// 旧的方式if (!string.IsNullOrEmpty(hello)){ Console.WriteLine($"{hello} has {hello.Length} letters.");}// 新的方式if (hello is { Length: >0 }){ Console.WriteLine($"{hello} has {hello.Length} letters.");}

属性模式相当灵活,你还可以把它用在数组上,对数组进行各种判断。比如判断可空字符串数组中的字符串元素是否为空或空白:

string?[]? greetings = new string[2];greetings[0] = "Hello world";greetings = null;// 旧的方式if (greetings != null && !string.IsNullOrEmpty(greetings[0])){ Console.WriteLine($"{greetings[0]} has {greetings[0].Length} letters.");}// 新的方式if (greetings?[0] is {Length: > 0} hi){ Console.WriteLine($"{hi} has {hi.Length} letters.");}

刚开始你可能会觉得阅读体验不太好,但用多了看多了,这种简洁的方法更有利于阅读。

使用逻辑模式简化多重判断

对于同一个值,把它与其它多个值进行比较判断,可以用 orand 逻辑模式简化,示例:

ConsoleKeyInfo userInput = Console.ReadKey();// 旧的方式if (userInput.KeyChar == 'Y' || userInput.KeyChar == 'y'){ Console.WriteLine("Do something.");}// 新的方式if (userInput.KeyChar is 'Y' or 'y'){ Console.WriteLine("Do something.");}

之前很多人不解 C# 9.0 为什么要引入 orand 逻辑关键字,通过这个示例就一目了然了。

后面还会继续分享一些 C# 9.0 的新姿势,也期待你的分享。

原文转载:http://www.shaoqun.com/a/489211.html

亚马逊t恤:https://www.ikjzd.com/w/1932

易联通:https://www.ikjzd.com/w/1854.html

斑马物联:https://www.ikjzd.com/w/1316


C#语言一贯秉承简洁优美的宗旨,每次升级都会带来一些语法糖,让我们可以使代码变得更简洁。本文分享两个使用C#9.0提升if语句美感的技巧示例。使用属性模式代替IsNullOrEmpty在任何你使用IsNullOrEmpty的时候,可以考虑这样替换:string?hello="helloworld";hello=null;//旧的方式if(!string.IsNullOrEmpt
mile:https://www.ikjzd.com/w/1746
网络星期一:https://www.ikjzd.com/w/80
马里亚纳群岛5.6级地震最新消息 中国网友感到地震是怎么回:http://tour.shaoqun.com/a/34401.html
连山鹰扬关有什么项目?鹰扬关怎么样?:http://tour.shaoqun.com/a/20059.html
厦门自助游去哪里好?:http://tour.shaoqun.com/a/42638.html

No comments:

Post a Comment