使用 C# 9.0 新语法提升 if 语句美感
生活随笔
收集整理的這篇文章主要介紹了
使用 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."); }剛開始你可能會覺得閱讀體驗不太好,但用多了看多了,這種簡潔的方法更有利于閱讀。
使用邏輯模式簡化多重判斷
對于同一個值,把它與其它多個值進行比較判斷,可以用?or?、and?邏輯模式簡化,示例:
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?邏輯關鍵字,通過這個示例就一目了然了。
后面還會繼續分享一些 C# 9.0 的新姿勢,也期待你的分享。
-
精致碼農
帶你洞悉編程與架構
↑長按圖片識別二維碼關注,不要錯過網海相遇的緣分
總結
以上是生活随笔為你收集整理的使用 C# 9.0 新语法提升 if 语句美感的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET架构小技巧(7)——做好小的项目
- 下一篇: 在 Azure App Service