为什么我不能使用

为什么我不能使用

本文介绍了为什么我不能使用“常量"?在范围内的 switch 语句中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码:

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",或者我得到,一个常数值是预期"

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

天堂到 Murgatroyd!难道它不能抬头看到 TABCONTROL_BASICINFO 是 0 吗?

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

推荐答案

如果你想让它成为编译器所关心的常量表达式,请将其声明为 const:

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;

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

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,
    ...
}

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

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 {
 }

可以变成:

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

这篇关于为什么我不能使用“常量"?在范围内的 switch 语句中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:13