尝试传递参数而不必考虑参数的顺序。 第一行是我希望能够做的事情,下面是我能够做的事情。
我想要的,两者都应该给出相同的结果
test.exe -word1 hello -word2 bye
test.exe -word2 bye -word1 hello
我有什么
test.exe hello bye
static void Main(string[] args)
{
console.line(args[0])
console.line(args[1])
}
你可以这样使用字符串输入:
test.exe -word1=hello -word2=bye
test.exe -word2=bye -word1=hello
然后你可以做这样的事情:
static void Main(string[] args)
{
// Single if the param is needed, else SingleOrDefault (to get null if the param. was not found
var word1 = args.Single(c => c.startsWith("-"+nameof(word1))
.Split(new char[] {'='})
.Last();
var word2 = args.Single(c => c.startsWith("-"+nameof(word2))
.Split(new char[] {'='})
.Last();
}
这是伪代码,我没有运行它 - 只是给你一个例子。
我什至不会打扰你,只是打了一巴掌:https://github.com/Tyrrrz/CliFx
您可以使用https://www.nuget.org/packages/Microsoft.Extensions.CommandLineUtils 中的CommandLineApplication
然后,您可以配置命令行参数和其他可用选项,并在以后显式使用它们。
例如:
var app = new CommandLineApplication()
{
Description = "CLI tool for copying messages from one queue to another",
Name = "copy-queue",
};
var sourceOption = _app.Option("--source|-s", $"The source queue name", CommandOptionType.SingleValue);
var destinationOption = _app.Option("--destination|-d", $"The destination queue name", CommandOptionType.SingleValue);
var profileOption = _app.Option("--profile|-p", $"AWS CLI profile (default: default)", CommandOptionType.SingleValue);
var regionOption = _app.Option("--region|-r", $"AWS region (default: us-east-1)", CommandOptionType.SingleValue);
var batchSizeOption = _app.Option("--batch-size|-b", $"Batch size (default: 10)", CommandOptionType.SingleValue);
_app.HelpOption("--help|-h|-?");
var name = Assembly.GetEntryAssembly().GetName();
_app.VersionOption("--version", name.Name + " " + name.Version);
_app.Invoke = () => ExecuteAsync().Result;
try
{
return _app.Execute(args);
}
catch (CommandParsingException cpe)
{
Console.WriteLine(cpe.Message);
return 1;
}
我假设在您的示例中 word1 将具有值"hello",但可能具有任何其他值,并且您对该值感兴趣。使用Array.IndexOf
您可以查找索引,然后获取索引更高的字符串:
int index1 = Array.IndexOf(args, "-word1");
string word1 = args[index1+1];
int index2 = Array.IndexOf(args, "-word2");
string word2 = args[index2+1];
您还可以考虑检查数组边界 (index1 < args.Length-1
) 以及index1
和index2
不是 -1,并在必要时显示相应的错误消息。