Switch statement with static fields

前端 未结 7 1986
执念已碎
执念已碎 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:42

    I'm assuming there's a reason you didn't declare those variables as const. That said:

    The switch statement is just shorthand for a bunch of if / else if statements. So if you can guarantee that PID_1, PID_2, and PID_3 will never be equal, the above is equivalent to this:

    if (pid == PID_1) {
        // Do something 1
    }
    else if (pid == PID_2) {
        // Do something 2
    }
    else if (pid == PID_3) {
        // Do something 3
    }
    else {
        // Do something default
    }
    

提交回复
热议问题