利用C#9.0新語法如何提升if語句美感
前言
C# 語言一貫秉承簡潔優(yōu)美的宗旨,每次升級都會帶來一些語法糖,讓我們可以使代碼變得更簡潔。本文分享兩個使用 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."); }
屬性模式相當靈活,你還可以把它用在數(shù)組上,對數(shù)組進行各種判斷。比如判斷可空字符串數(shù)組中的字符串元素是否為空或空白:
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 邏輯關(guān)鍵字,通過這個示例就一目了然了。
后面還會繼續(xù)分享一些 C# 9.0 的新姿勢,也期待你的分享。
總結(jié)
到此這篇關(guān)于利用C#9.0新語法如何提升if語句美感的文章就介紹到這了,更多相關(guān)C#9.0新語法提升if語句內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VS?Code里使用Debugger?for?Unity插件調(diào)試的方法(2023最新版)
Debugger for Unity是一個非正式支持的,官方推薦的,應用最廣的,Visual Studio Code上的Unity調(diào)試插件,這篇文章主要介紹了VS?Code里使用Debugger?for?Unity插件進行調(diào)試(2023最新版),需要的朋友可以參考下2023-02-02混合語言編程—C#使用原生的Directx和OpenGL繪圖的方法
本文要說的是混合C#和C/C++語言編程,在C#的Winform和WPF下使用原生的Direct和OpenGL進行繪圖2013-09-09Unity3D實現(xiàn)飛機大戰(zhàn)游戲(1)
這篇文章主要為大家詳細介紹了Unity3D實現(xiàn)飛機大戰(zhàn)游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06