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

        共 1644字,需瀏覽 4分鐘

         ·

        2021-01-11 20:21

        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.");
        }

        屬性模式相當(dāng)靈活,你還可以把它用在數(shù)組上,對數(shù)組進行各種判斷。比如判斷可空字符串?dāng)?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 的新姿勢,也期待你的分享。







        回復(fù) 【關(guān)閉】學(xué)關(guān)
        回復(fù) 【實戰(zhàn)】獲取20套實戰(zhàn)源碼
        回復(fù) 【被刪】學(xué)
        回復(fù) 【訪客】學(xué)
        回復(fù) 【小程序】學(xué)獲取15套【入門+實戰(zhàn)+賺錢】小程序源碼
        回復(fù) 【python】學(xué)微獲取全套0基礎(chǔ)Python知識手冊
        回復(fù) 【2019】獲取2019 .NET 開發(fā)者峰會資料PPT
        回復(fù) 【加群】加入dotnet微信交流群
        瀏覽 28
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
          
          

            1. 乱色综合 | a一级大片 | 亚洲性爱小说图片 | 91婷婷国产一区二区三区 | 色逼影视|