Switch statement with static fields

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

    It looks like those string values should simply be constant.

    public const string PID_1 = "12";
    public const string PID_2 = "13";
    public const string PID_3 = "14";
    

    If that's not an option (they are actually changed at runtime), then you can refactor that solution into a series of if/else if statements.

    As to why the case statements need to be constant; by having them be constant it allows the statement to be much more heavily optimized. It is actually more efficient than a series of if/else if statements (although not dramatically so if you don't have lots of conditional checks that take a long time). It will generate the equivalent of a hash table with the case statement values as keys. That approach couldn't be used if the values can change.

提交回复
热议问题