【问题标题】:Is there an easier way to pass an array as command line argument using Microsoft.Extensions.Configuration?有没有更简单的方法使用 Microsoft.Extensions.Configuration 将数组作为命令行参数传递?
【发布时间】:2022-01-27 00:19:29
【问题描述】:

我正在开发一个 .net 通用主机应用程序,我想通过命令行传递一些配置,然后将其绑定到一个对象:

public class CommandArgs
{
   public string Mode { get; set; }
   public string[] Logins { get; set; }
}

此时我知道我可以像这样传递Logins 数组:

--CommandArgs:Logins:0=Login0 --CommandArgs:Logins:1=Login1 ...

问题在于'--CommandArgs:Logins:{index}' 语句的重复数量。 我曾尝试使用 switch 映射来减少重复句子:

var switchMappings = new Dictionary<string, string>
{
   "--Logins", "CommandArgs:Logins"
};
    
    configBuilder.AddCommandLine(args, switchMappings);

实现类似的目标:

--Logins:0=Login0 --Logins:1=Login1

但它似乎不是那样工作的。

有没有办法在传递数组时使用开关映射或任何更简单的语法?

【问题讨论】:

    标签: c# .net-core command-line-arguments asp.net-core-hosted-services


    【解决方案1】:

    你可以在没有switchMappings 的情况下做到这一点并像这样更改参数:

    //--Logins:0 Login0 --Logins:1 Login1
    configBuilder.AddCommandLine(args);
    var config=configBuilder.Build();
    var logins= config.GetSection("Logins").GetChildren().Select(x => x.Value).ToArray();
    

    经过测试,工作正常。

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 2020-02-26
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2012-03-25
      • 2014-12-08
      相关资源
      最近更新 更多