gpt4 book ai didi

c# - 为什么我不能在范围内的 switch 语句中使用 "constant"?

转载 作者:可可西里 更新时间:2023-11-01 08:50:36 25 4
gpt4 key购买 nike

使用这段代码:

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

关于c# - 为什么我不能在范围内的 switch 语句中使用 "constant"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com