假设我有一堆静态字段的,我想在交换机使用它们:
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语句的。
至于为何case语句需要保持恒定; 通过使它们是恒定的,它允许的语句中更大量优化。 它实际上是不是一系列更有效的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<string, Action>
{
{PID_1, ()=>Console.WriteLine("one")},
{PID_2, ()=>Console.WriteLine("two")},
{PID_3, ()=>Console.WriteLine("three")},
};
var pid = PID_1;
dict[pid]();
}
案例参数应该是在编译时间常数。
尝试使用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_1
, PID_2
和PID_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<Something, Action>
:
static Dictionary<string, Action> switchReplacement =
new Dictionary<string, Action>() {
{ 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
}