[C#] 用 switch expression 重構你的判斷邏輯

  • 196
  • 0

自己在寫程式的時候,我是一個很習慣用大量 if 的人,對我個人來說其實可閱讀性比較強,但是這的確不是一個好習慣

於是我想說透過 ChatGPT 看看新的 C# 語法有沒有可以取代我現在的習慣,順便改掉這壞習慣..

這時候我找到一個關鍵字 switch expression - pattern matching expressions using the switch keyword

於是我就簡單測試一下,這邊我都是用 string 來做設計案例,以便好讀懂

           var userType = "PREMIUM";

            var result1 = userType switch
            {
                "PLUS" =>"CALL_PLUS",
                "PREIUM" => "Call_Preium",
                "Ultimate" => "Call_UTIMATE",
                _ => "CALL_DEFAULT",
            } ;

現在可以把 code 變得很簡潔,之前我不喜歡使用傳統 switch 的原因就是因為他的排版方式不是我個人所喜好的( 個人習慣問題)

現在這樣的寫法就可以變得很簡單。

但是這時候我有一個問題 他可不可以做判斷 這時候,就要用到 判斷 string.IsNullOrEmpty 就要用到 pattern matching + guard


            var userType = "";

            var result = userType switch
            {
               //要使用 when 關鍵字來使用
                var t when string.IsNullOrEmpty(t) => "DEFAULT",
                "PLUS" => "CALL_PLUS",
                "PREMIUM" => "CALL_PREMIUM",
                "Ultimate" => "CALL_ULTIMATE",
                _ => "CALL_DEFAULT"
            };

最後,因為我常用的方法都是判斷條件之後都要去呼叫相關的 Logic function ,這時候不能只有回傳值,但是 expressions 的作法

都必須要有回傳值,所以只能在小改寫一下 code 



            var userType = "";


            var result = userType switch
            {
                var t when string.IsNullOrEmpty(t) =>
                    new Func<string>(() => { Console.WriteLine("Default"); return "CALL_DEFAULT"; })(),

                "PLUS" =>
                    new Func<string>(() => { Console.WriteLine("Plus"); return "CALL_PLUS"; })(),

                "PREMIUM" =>
                    new Func<string>(() => { Console.WriteLine("Premium"); return "CALL_PREMIUM"; })(),

                "Ultimate" =>
                    new Func<string>(() => { Console.WriteLine("Ultimate"); return "CALL_ULTIMATE"; })(),

                _ =>
                    new Func<string>(() => { Console.WriteLine("Default"); return "CALL_DEFAULT"; })(),
            };

            Console.WriteLine(result);
            
            

大概筆記到這邊,對很多人來說可能很簡單,不過畢竟很多時候程式寫久了,要改變一個習慣就是比較難一點畢竟第一時間不會想到


 

---

請你暫時把你的勇氣給我 在夢想快消失的時候 讓我的 Code 用力的穿過天空 為愛我的人做一秒英雄 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力…

Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer.