未提供System.CommandLine选项时,如何回退读取app.config配置?
实现命令行Option的配置回退逻辑
不用预处理args参数,我们可以借助.NET System.CommandLine库的CommandInvocationContext来判断Option是否被用户显式指定,从而实现「用户输入→app.config配置→默认值」的回退逻辑。
修改后的完整代码实现
static async Task<Int32> Main(String[] args) { // 定义轮询频率选项 Option<Int32> pollingRateOption = new Option<Int32>( aliases: new[] { "-r", "--Polling-Rate" }, description: "轮询频率,单位为毫秒。", isDefault: true, parseArgument: result => { if (Int32.TryParse(result.Tokens.Single().Value, out Int32 pr)) { if (pr < 1 || pr > 1000) { result.ErrorMessage = "轮询频率必须是1-1000之间的整数"; } return pr; } else { result.ErrorMessage = "轮询频率必须是1-1000之间的整数"; return 0; // 该值会被解析逻辑忽略 } } ); pollingRateOption.ArgumentHelpName = "1-1000"; pollingRateOption.Arity = ArgumentArity.ExactlyOne; pollingRateOption.SetDefaultValue(5); // 最终兜底的默认值 RootCommand rootCommand = new RootCommand($"{AppName}"); rootCommand.AddOption(pollingRateOption); // 重写Handler,加入上下文判断逻辑 rootCommand.SetHandler((pollingRateValue, context) => { int finalPollingRate; // 获取当前Option的解析结果,判断是否为用户显式输入 var optionResult = context.ParseResult.FindResultFor(pollingRateOption); if (optionResult != null && !optionResult.IsImplicit) { // 用户主动提供了参数,直接用解析后的值 finalPollingRate = pollingRateValue; } else { // 用户未输入,先尝试读取app.config的配置项 var configValue = System.Configuration.ConfigurationManager.AppSettings["PollingRate"]; if (Int32.TryParse(configValue, out int configPr) && configPr >= 1 && configPr <= 1000) { finalPollingRate = configPr; } else { // 配置文件无有效值,使用Option的默认值 finalPollingRate = pollingRateValue; } } Run(finalPollingRate); }, pollingRateOption, CommandInvocationContext.Current); return await rootCommand.InvokeAsync(args); }
关键逻辑说明
CommandInvocationContext.ParseResult:获取命令行解析后的完整结果集合,通过FindResultFor定位到目标Option的解析记录optionResult.IsImplicit:标记该值是否为系统自动填充的默认值——true表示用户未显式输入,false表示用户主动提供了参数- 优先级顺序:用户显式输入的参数 > app.config中的配置值 > Option预设的默认值
内容的提问来源于stack exchange,提问作者Xorcist
相关产品推荐
相关产品推荐

