带有静态字段的 switch 语句

Switch statement with static fields(带有静态字段的 switch 语句)

本文介绍了带有静态字段的 switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 中使用非常量语句.我想了解这种设计的意图是什么.我应该如何在 c# 中执行上述操作?

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 语句更有效(尽管如果您没有 lots 需要很长时间的条件检查,效果并不明显).它将生成一个等效的哈希表,其中 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 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:带有静态字段的 switch 语句

基础教程推荐