[C#] 使用表驅動法替代IF Else 和 Switch Case


  當系統功能增加時,有的時候需要用到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));;
    }
}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM