我在winforms c#应用程序中有两个表单。
第一种形式是登录表单,它对活动目录执行身份验证,并进行许多授权检查,允许用户继续。在表单上还有一个下拉选项:
Environment:
Development
Staging
Production
用户经过审核后,我会在隐藏登录表单并显示主应用程序表单之前设置以下内容:
Globals.environment = ((string)this.cmboEnvironment.SelectedItem).ToLower();
Globals.cs
public partial class Globals
{
// A flag which denotes the environment that the tool should run against (staging/development/production)
public static string environment;
public static string server;
static Globals()
{
switch (environment)
{
case "development":
server = "Dev-Server";
break;
case "staging":
server = "Staging-Server";
break;
case "production":
server = "Production-Server";
break;
default:
server = "Dev-Server";
break;
}
}
}
我发现无论我选择哪个下拉列表,服务器值始终设置为Dev-Server。
我认为发生的事情是Globals对象在调用设置环境值之前被实例化,因此case语句默认为"默认:"案件。
我无法弄清楚如何在填充所有其他全局值之前设置环境。任何人都可以帮助我吗?
由于 布拉德
答案 0 :(得分:1)
您的猜测是正确的default
案例一直在执行,这是因为,输入environment
与给定案例中的任何一个都不匹配(开关对给定的情况执行区分大小写的比较表达和案件)。您需要更改case
与DropDown中的相同,或使用.ToLower()
,如下所示:
switch (environment.ToLower())
{
case "development":
server = "Dev-Server";
break;
case "staging":
server = "Staging-Server";
break;
case "production":
server = "Production-Server";
break;
default:
server = "Dev-Server";
break;
}
答案 1 :(得分:1)
你可以这样做:
public partial class Globals
{
// A flag which denotes the environment that the tool should run against (staging/development/production)
public static string environment;
public static string server;
public static void SetEnvironment(string env)
{
environment = env;
switch (env)
{
case "development":
server = "Dev-Server";
break;
case "staging":
server = "Staging-Server";
break;
case "production":
server = "Production-Server";
break;
default:
server = "Dev-Server";
break;
}
}
}
然后:
Globals.SetEnvironment(((string)this.cmboEnvironment.SelectedItem).ToLower());