C# 覆盖app.config中的临时值
在我的代码中,有几个地方可以从app.config中检索serviceurl,例如C# 覆盖app.config中的临时值,c#,winforms,configurationmanager,C#,Winforms,Configurationmanager,在我的代码中,有几个地方可以从app.config中检索serviceurl,例如ConfigurationManager.AppSettings[“ServerURL”] 现在,我想让用户能够将服务url指定为命令行参数。如果未指定参数,则必须使用app.config中的serviceurl 总的来说,我可以做到以下几点: if(args[0] != null) ConfigurationManager.AppSettings["ServerURL"] = args[0] 它似乎可以工作,但
ConfigurationManager.AppSettings[“ServerURL”]代码>
现在,我想让用户能够将服务url指定为命令行参数。如果未指定参数,则必须使用app.config中的serviceurl
总的来说,我可以做到以下几点:
if(args[0] != null)
ConfigurationManager.AppSettings["ServerURL"] = args[0]
它似乎可以工作,但我可以相信AppSettings[“ServerURL”]没有从app.config重新加载吗?我知道ConfigurationManager.RefreshSection,但它没有被使用。您应该使用另一个类包装ConfigurationManager
并提供值替换逻辑,而不是从code更改AppSettings
值:
public static class Conf {
public static string ServerURLOverride { get; set; }
public static string ServerUrl {
get { return ServerURLOverride ?? ConfigurationManager.AppSettings["ServerURL"]; }
}
}
在Main()
中:
这也将简化单元测试
if (args.Length > 0 && args[0] != null)
Conf.ServerURLOverride = args[0];