这是来自较新的C#家伙,
我在这里提出的不同问题来回反复,但我没有找到任何可以直接回答我需要知道的事情。
我有一个控制台应用程序,我想通过命令行传递参数。这是我到目前为止,它正在为一个论点工作,现在我要添加另一个,但我似乎无法弄清楚从哪里开始。
static void Main(string[] args)
{
if (args == null || args.Length== 0)
{
Console.WriteLine("that's not it");
help();
}
else
{
for (int i = 0; i < args.Length; i++)
{
backupfolder = args[i];
}
checks();
}
}
如果我从我的其他声明中取出所有内容,我该如何设置args是什么并分配?以下是否有效?
static void Main(string[] args)
{
if (args == null || args.Length== 0)
{
Console.WriteLine("that's not it");
help();
}
else
{
string backupfolder = args[0];
string filetype = args[1];
checks();
}
}
答案 0 :(得分:7)
在尝试从中检索值之前,您需要检查args
数组的长度:
static void Main(string[] args)
{
// There must be at least 2 command line arguments...
if (args == null || args.Length < 2)
{
Console.WriteLine("that's not it");
help();
}
else
{
string backupfolder = args[0];
string filetype = args[1];
checks();
}
}
另一个选项,如果你想允许只传递一些预期的参数:
static void Main(string[] args)
{
// There must be at least 1 command line arguments.
if (args == null || args.Length < 1)
{
Console.WriteLine("that's not it");
help();
}
else
{
// You already know there is at least one argument here...
string backupfolder = args[0];
// Check if there is a second argument,
// provide a default value if it's missing
string filetype = (args.Length > 1) ? args[1] : "" ;
checks();
}
}