使用此代码:
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; }