为什么我不能在范围内的switch语句中使用“常量”?

时间:2012-03-22 23:04:33

标签: c# .net switch-statement

使用此代码:

public partial class Form1 : Form
{
    private static readonly int TABCONTROL_BASICINFO = 0;
    private static readonly int TABCONTROL_CONFIDENTIALINFO = 1;
    private static readonly int TABCONTROL_ROLESANDSECURITY = 2;
    private static readonly int TABCONTROL_INACTIVEINFO = 3;
. . .
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
    case TABCONTROL_BASICINFO:
        if (currentNode == "NodeBuckingham") {
        } else if (currentNode == "NodeNamath") {
        } else if (currentNode == "NodeParsons") {
        } else {
        }
    break;

...我必须用“0”替换“TABCONTROL_BASICINFO”,否则我会得到,“一个常数值是 预期“

天堂到Murgatroyd!它不能查找并看到TABCONTROL_BASICINFO为0?

4 个答案:

答案 0 :(得分:19)

如果要在编译器方面使其成为常量表达式,请将其声明为const

// Note that static readonly is implied here
private const int TABCONTROL_BASICINFO = 0;

或遵循.NET命名约定......

private const int TabControlBasicInfo = 0;

或者使用枚举,因为你基本上得到了一组固定的值:

private enum TabControlType
{
    // Could ditch the explicit values here if you want
    BasicInfo = 0,
    ConfidentialInfo = 1,
    ...
}

顺便说一下,你也可以在C#中打开字符串,所以这个:

 if (currentNode == "NodeBuckingham") {
 } else if (currentNode == "NodeNamath") {
 } else if (currentNode == "NodeParsons") {
 } else {
 }

可以成为:

 switch (currentNode) {
     case "NodeBuckingham":
         ...
         break;
     case "NodeNamath":
         ...
         break;
     case "NodeParsons":
         ...
         break;
     default:
         ...
         break;
 }

答案 1 :(得分:13)

readonly变量不是常量。该值在编译时是未知的,而是可以在声明中(如您所做)或在类构造函数(在本例中为您的类的静态构造函数)中初始化。

有关详情,请参阅

http://msdn.microsoft.com/en-us/library/acdd6hb7(v=vs.71).aspx

您可以将其更改为:

private const int TABCONTROL_BASICINFO = 0; 

除非您需要计算某些内容来初始化变量,否则请将其声明为const。效率稍高。

答案 2 :(得分:7)

这不是一个常数;它是只读变量如果您希望它是常量,请将其标记为常量。

private const int TabControlBasicInfo = 0;

甚至更好:

private enum TabControl
{
    BasicInfo,
    ...
}
...
switch(whatever)
{
    case TabControl.BasicInfo:

答案 3 :(得分:5)

静态只读不是常量变量。它可以初始化。而“const”是不变的。