Switch statement with static fields

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

    ... C# doesn't allow non-const statement inside switch...

    If you can't use:

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

    You can use a dictionary :)

    ....
    public static string PID_1 = "12";
    public static string PID_2 = "13";
    public static string PID_3 = "14";
    
    
    
    // Define other methods and classes here
    
    void Main()
    {
       var dict = new Dictionary
       {
        {PID_1, ()=>Console.WriteLine("one")},
        {PID_2, ()=>Console.WriteLine("two")},
        {PID_3, ()=>Console.WriteLine("three")},
       };
       var pid = PID_1;
       dict[pid](); 
    }
    

提交回复
热议问题