當系統功能增加時,有的時候需要用到Switch Case去判斷執行方法,當功能越來越多的時候這種方法就會顯得臃腫,最優的做法應該是通過表驅動取代Switch Case,下面的代碼定義了用戶處理的枚舉,以及用戶執行的相關操作。
我們通過把方法名放到string[] 數組中,當調用的時候通過反射獲取方法並執行,代碼如下:
using System; public class Program { static void Main(string[] args) { Console.WriteLine("Please input th user name:"); var userName=Console.ReadLine(); UserActionProcessor ap = new UserActionProcessor(); //Reflection:Get the name of method; var method = typeof(UserActionProcessor).GetMethod(GetUserActionFromTable(UserAction.LoginInSystem)); method.Invoke(ap,new object[]{userName}); Console.ReadLine(); } //Table Drive Replace the Switch static string GetUserActionFromTable(UserAction userAction) { string[] actionArray=new string[]{"Login","OpenIE","OpenChrome"}; return actionArray[(int)userAction]; } //User Action Enum enum UserAction { LoginInSystem, OpenIEBrowser, OpenChromeBrowser } } public class UserActionProcessor { public void OpenIE(string userName) { //Process ... Console.WriteLine(string.Format("{0} open IE!",userName)); } public void OpenChrome(string userName) { //Process... Console.WriteLine(string.Format("{0} open Chrome!",userName)); } public void Login(string userName) { //Process... Console.WriteLine(string.Format("{0} Login Success!",userName));; } }