加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:34:46 所属栏目:百科 来源:网络整理
导读:使用此代码: 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
使用此代码:
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吗?

解决方法

如果要使编译器成为常量表达式,请将其声明为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;
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读