C# 使用多个参数

C# Using Multiple Arguments

这是来自 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();
    }
}

如果我从 else 语句中取出所有内容,我该如何设置参数并赋值?下面的方法行得通吗?

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();
    }
}

在尝试从中检索值之前,您需要检查 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();
    }
}