我正在开发一个 .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/