軟體開發時,有時候會遇到主流程中突然冒出一堆 switch case 的判斷
雖然有 #region #endregion 可以縮排,但在偵錯時候就會需要在switch中徘徊
因此好奇別人switch case都是怎麼改善
Google大神就被我看見這篇文章 [C#] Refactor – 重構 Switch case 陳述句
我這邊也簡單整理一下留下筆記,未來需要使用可以快速進入狀況
改善的寫法有點像JavaScript
原本Switch Case
switch (status) { case "Success": Console.WriteLine("成功"); break; case "Fail": Console.WriteLine("失敗"); break; case "Wait": Console.WriteLine("等待中"); break; case "Cancel": Console.WriteLine("取消"); break; }
改良版 ( Enum + Dictionary<enum, Action> )
public enum Status { Success, Fail, Wait, Cancel } private Dictionary<Status, Action> _statusHandle = new Dictionary<Status, Action>() { { Status.Success, ()=> Console.WriteLine("成功") }, { Status.Fail, ()=> Console.WriteLine("失敗") }, { Status.Wait, ()=> Console.WriteLine("等待中") }, { Status.Cancel, ()=> Console.WriteLine("取消") } }; if (_statusHandle.ContainsKey(Status.Success)) _statusHandle[Status.Success].Invoke(); // output: 成功
原本Switch Case
string name = "申購股票"; switch (status) { case "Success": Console.WriteLine($"{name}成功"); break; case "Fail": Console.WriteLine($"{name}失敗"); break; case "Wait": Console.WriteLine($"{name}等待中"); break; case "Cancel": Console.WriteLine($"{name}取消"); break; }
改良版 ( Enum + Dictionary<enum, Func<string, string>> )
public enum Status { Success, Fail, Wait, Cancel } private Dictionary<Status, Func<string, string>> _statusHandle = new Dictionary<Status, Func<string, string>>() { { Status.Success, name => Console.WriteLine($"{name}成功") }, { Status.Fail, name => Console.WriteLine($"{name}失敗") }, { Status.Wait, name => Console.WriteLine($"{name}等待中") }, { Status.Cancel, name => Console.WriteLine($"{name}取消") } }; if (_statusHandle.ContainsKey(Status.Success)) _statusHandle[Status.Success].Invoke("申購股票"); // output: 申購股票成功