带静态字段的switch语句 [英] Switch statement with static fields
问题描述
假设我有一堆静态字段,并且想在开关中使用它们:
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 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#不允许在switch中使用非const语句。我想了解这种设计的意图。
Since C# doesn't allow non-const statement inside switch. I want to understand what is the intention of this kind of design. How should I do something like above in c#?
推荐答案
这些字符串值应该只是常量。
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 / else if语句。
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.
为什么case语句需要保持不变;通过使它们恒定,可以使语句的优化程度更高。它实际上比一系列的if / else if语句更有效(尽管效果不是很明显,所以如果您没有很多条条件检查需要很长时间)。它将生成与case语句值作为键的哈希表等效的表。如果值可以更改,则无法使用该方法。
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.
这篇关于带静态字段的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!