c# - 是否有更简单的方法使用 Microsoft.Extensions.Configuration 将数组作为命令行参数传递?

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

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

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}”句子的重复数量。 我尝试使用开关映射来减少重复句子:

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

实现类似的目标:

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

但似乎不是这样工作的。

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

最佳答案

您可以在没有 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();

经过测试,工作正常。

关于c# - 是否有更简单的方法使用 Microsoft.Extensions.Configuration 将数组作为命令行参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70505561/

相关文章:

c# - Parser.Default.ParseArguments 始终返回 false

c# - 如何编写模拟不同用户的测试?

c# - 发送批量电子邮件时出错 "An asynchronous call is already in progress. It must be completed or canceled before you can call this method"

c# - 按需输出使用 DragonFruit 的帮助

docker - 无法加载共享库 'kernel32.dll' 或其依赖项之一

windows - 跟踪在 VB.net 应用程序中调用的外部 .EXE 的参数

c# - 使用 XML 数据类型调用存储过程

c# - 哪个事件会通知我滚动条中的滚动已完成?

reactjs - 如何使用 React.js 在 Microsoft botframework 网络聊天中添加 AutoComplete/AutoSuggestion

c++ - 如何将 argv[1] 传递给带有 0 个参数的函数?