如何在没有 if 的情况下在 C# 中的 switch case 中使用 web.config 值,否则循环“需要一个常量值”。

MST*_*dev 6 c# web-config constants switch-statement

下面是开关盒

switch (strID)
{
    case ConfigurationManager.AppSettings["Key1"].ToString():
        Label1.Visible = true;
        break;
    case ConfigurationManager.AppSettings["Key2"].ToString():
        Label2.Visible = true;
        break;
    case ConfigurationManager.AppSettings["Key3"].ToString():
        Label3.Visible = true;
        break;
    default:
        Label1.Visible = true;
        break;
}
Run Code Online (Sandbox Code Playgroud)

但它给出了错误“期望一个常数值”。

我知道 switch 语句中不能有变量。但是有什么办法吗?

小智 3

在 case 语句中只能使用常量值。

更好的是你可以使用 if 语句,例如

if(ConfigurationManager.AppSettings["Key1"].ToString() == strID)
{
   Label1.Visible = true;
}
else if(ConfigurationManager.AppSettings["Key2"].ToString() == strID)
{
   Label2.Visible = true;
}
Run Code Online (Sandbox Code Playgroud)

。。。。。。。

else
{
    //default
}
Run Code Online (Sandbox Code Playgroud)