如何将一个空参数传递给主 class?

How to pass one null parameters to the main class?

下面的示例代码从 cmd 中获取两个字符串参数,例如

c:\myprogram.exe bobby henn

输出

first name is bobby
last name is henn

但是当我只传递一个参数时它抛出一个错误,即使我在 if case

中指定了长度
c:\myprogram.exe bobby 

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at command.Program1.Main(String[] args)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace command
{
   public class Program
    {
       public void ben(string bobby, string x)
        {

          if (bobby == null |  x.Length < 1)
            {
                Console.WriteLine("Empty value, pass any parameter");
            }

            else
             {

                Console.WriteLine("First Name is " + bobby);
                Console.WriteLine("Last Name is " + x);
                Console.ReadLine();
            }
        }

    }

    class Program1
    {
        static void Main(string[] args)
        {
         Program glb = new Program();
         glb.ben(bobby:args[0],x:args[1]);
        }
    }

}

还有没有其他方法可以调用 main 方法的参数而不是 bobby:args[0],x:args[1]

static void Main(string[] args)
        {
         Program glb = new Program();

         if(args.length==2) 
         glb.ben(args[0],x:args[1]);
         else
         glb.ben(args[0]);
        }

并改变这个

     public void ben(string bobby, string x = null)

您应该始终将清理用户输入作为第一步。在这种情况下,如果两个参数都需要,您可以打印一条错误消息然后退出。

关于你的第二个问题,你可以使用 EnvironmentGetCommandLineArgs() 但这 returns 无论如何都是一个字符串数组。 https://msdn.microsoft.com/en-us/en-en/library/system.environment.getcommandlineargs(v=vs.110).aspx

除了检查输入参数数量的答案外:只要您按定义的顺序传递参数,就不需要在参数名称前加上前缀

glb.ben(bobby:args[0],x:args[1]);

可以简化为

glb.ben(args[0],args[1]);

如果你想以不同的顺序传递参数,那么你可以使用

glb.ben(x:args[1], bobby:args[0]);

您可以使用 System.LinqElementAtOrDefault 扩展方法,而不是方括号运算符:

glb.ben(bobby:args.ElementAtOrDefault(0), x:args.ElementAtOrDefault(1));

如果索引超出给定数组的范围,它将 return null,而不是抛出异常。