[尝试传递参数而不必考虑参数的顺序。第一行是我想要做的,下面是我能够做的。
我想要什么都应该给出相同的结果
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])
}
我假设在您的示例中word1将具有值“ hello”,但可能具有任何其他值,并且您对该值感兴趣。使用Array.IndexOf
,您可以查找索引,然后使用索引高一的字符串来获取字符串:
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
不是-1,并在必要时显示适当的错误消息。
您可以像这样使用字符串输入:
index2
然后您可以执行以下操作:
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中的CommandLineApplication
然后,您可以配置命令行参数和其他可用选项,并在以后显式使用它们。
例如:
https://www.nuget.org/packages/Microsoft.Extensions.CommandLineUtils