[C#] IF Else 및 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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.