1. 程式人生 > >使用 C# 9.0 新語法提升 if 語句美感

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

C# 語言一貫秉承簡潔優美的宗旨,每次升級都會帶來一些語法糖,讓我們可以使程式碼變得更簡潔。本文分享兩個使用 C# 9.0 提升 `if` 語句美感的技巧示例。 ## 使用屬性模式代替 IsNullOrEmpty 在任何你使用 `IsNullOrEmpty` 的時候,可以考慮這樣替換: ```csharp 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."); } ``` 屬性模式相當靈活,你還可以把它用在陣列上,對陣列進行各種判斷。比如判斷可空字串陣列中的字串元素是否為空或空白: ```csharp 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 ` 邏輯模式簡化,示例: ```csharp 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 的新姿勢,也期待你的分享。