用静态字段切换语句

假设我有一堆静态字段,我想在交换机中使用它们:

public static string PID_1 = "12"; public static string PID_2 = "13"; public static string PID_3 = "14"; switch(pid) { case PID_1: //Do something 1 break; case PID_2: //Do something 2 break; case PID_3: //Do something 3 break; default: //Do something default break; } 

由于C#不允许在开关内部使用非const语句。 我想了解这种设计的意图是什么。 我应该如何在c#中执行上述操作?

看起来这些字符串值应该只是常量。

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

如果这不是一个选项(它们实际上是在运行时更改的),那么您可以将该解决方案重构为一系列if / else if语句。

至于为什么案例陈述需要保持不变; 通过使它们保持不变,它可以使语句更加优化。 它实际上比一系列if / else if语句更有效(尽管如果你没有很多条件检查需要花费很长时间,那么效果并不是很明显)。 它将生成等效的哈希表,并将case语句值作为键。 如果值可以改变,则不能使用该方法。

… C#不允许在开关内部使用非const语句…

如果你不能使用:

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

你可以用字典:)

 .... 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](); } 

Case参数在编译时应该是常量。

尝试使用const代替:

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

我假设有一个原因你没有将这些变量声明为const 。 那说:

switch语句只是一堆if / else if语句的简写。 因此,如果您可以保证 PID_1PID_2PID_3 永远不会相等,则上述内容相当于:

 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 } 

接近这个的规范方法 – 如果你的静态字段实际上不是常量 – 就是使用Dictionary

 static Dictionary switchReplacement = new Dictionary() { { 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(); 

为什么你不使用枚举?
枚举关键字:
http://msdn.microsoft.com/en-us/library/sbbt4032%28v=vs.80%29.aspx

在您的情况下,它可以通过枚举轻松处理:

 public enum MyPidType { PID_1 = 12, PID_2 = 14, PID_3 = 18 }