Switch statement with static fields

前端 未结 7 1985
执念已碎
执念已碎 2021-01-11 14:28

Suppose I have a bunch of static fields and I want to use them in switch:

public static string PID_1 = \"12\";
public static string PID_2 = \"13\";
public st         


        
相关标签:
7条回答
  • 2021-01-11 14:57

    The canonical way to approach this -- if your static fields are not actually constants -- is to use a Dictionary<Something, Action>:

    static Dictionary<string, Action> switchReplacement = 
        new Dictionary<string, Action>() {
            { PID_1, action1 }, 
            { PID_2, action2 }, 
            { PID_3, action3 }};
    
    // ... Where action1, action2, and action3 are static methods with no arguments
    
    // Later, instead of switch, you simply call
    switchReplacement[pid].Invoke();
    
    0 讨论(0)
提交回复
热议问题