C# 语言一向秉承简洁优美的宗旨,每次升级都会带来一些语法糖,让咱们能够使代码变得更简洁。本文分享两个使用 C# 9.0 提高 if
语句美感的技巧示例。php
使用属性模式代替 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."); }
刚开始你可能会以为阅读体验不太好,但用多了看多了,这种简洁的方法更有利于阅读。架构
使用逻辑模式简化多重判断
对于同一个值,把它与其它多个值进行比较判断,能够用 or
、and
逻辑模式简化,示例:spa
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 为何要引入 or
、and
逻辑关键字,经过这个示例就一目了然了。code
后面还会继续分享一些 C# 9.0 的新姿式,也期待你的分享。图片
-字符串
精致码农
string
带你洞悉编程与架构it
↑长按图片识别二维码关注,不要错过网海相遇的缘分