Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 覆盖app.config中的临时值_C#_Winforms_Configurationmanager - Fatal编程技术网

C# 覆盖app.config中的临时值

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] 它似乎可以工作,但

在我的代码中,有几个地方可以从app.config中检索serviceurl,例如
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];