[C#] IF Else 및 Switch Case 대신 테이블 제어 사용

4850 단어
시스템 기능이 증가할 때 어떤 때는 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));;
    }
}

 
 
 
 
전재 대상:https://www.cnblogs.com/brucezhang80/p/Table_Drive_Replace_Switch_Case.html

좋은 웹페이지 즐겨찾기