Why can I not use a “constant” within a switch statement within scope?

时光毁灭记忆、已成空白 提交于 2019-12-23 07:08:30

问题


With this code:

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;

...I have to replace "TABCONTROL_BASICINFO" with "0", or I get, "A constant value is expected"

Heavens to Murgatroyd! Can't it look up and see that TABCONTROL_BASICINFO is 0?


回答1:


If you want to make it a constant expression as far as the compiler is concerned, declare it as a const:

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

Or follow .NET naming conventions...

private const int TabControlBasicInfo = 0;

Or use an enum, given that you've basically got a fixed set of values:

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

By the way, you can also switch on strings in C#, so this:

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

Can become:

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



回答2:


A readonly variable is not a constant. The value is not known at compile time, but rather can be initialized either in the declaration (as you have done) or in the class constructor (in this case, the static constructor for your class).

For more see

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

You can change it to:

private const int TABCONTROL_BASICINFO = 0; 

Unless you need to compute something to initialize the variable, declare it as const. It will be slightly more efficient.




回答3:


That's not a constant; it's a read-only variable. If you want it to be a constant then mark it as a constant.

private const int TabControlBasicInfo = 0;

Or even better:

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



回答4:


Static readonly isn't a constant variable. It can be initialized. Whereas "const" is constant.



来源:https://stackoverflow.com/questions/9831841/why-can-i-not-use-a-constant-within-a-switch-statement-within-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!