【问题标题】:Overwrite value from app.config temporary临时覆盖 app.config 中的值
【发布时间】:2012-09-18 22:43:36
【问题描述】:

在我的代码中的几个地方,一个 serviceurl 是从 app.config 中检索出来的,像这样ConfigurationManager.AppSettings["ServerURL"];

现在我想让用户可以将服务 url 指定为命令行参数。如果未指定参数,则必须使用 app.config 中的 serviceurl。

在 Main 我可以执行以下操作:

if(args[0] != null)
ConfigurationManager.AppSettings["ServerURL"] = args[0]

它似乎工作,但我可以依靠 AppSettings["ServerURL"] 不是从 app.config 重新加载的吗?我知道 ConfigurationManager.RefreshSection 但没有使用。

【问题讨论】:

    标签: c# winforms configurationmanager


    【解决方案1】:

    您应该有另一个包装ConfigurationManager 并提供值替换逻辑的类,而不是从代码中更改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];
    

    这也将简化单元测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      相关资源
      最近更新 更多