【问题标题】:How to check number of command line arguments + exception handling如何检查命令行参数的数量+异常处理
【发布时间】:2019-05-23 06:48:43
【问题描述】:

如何检查输入的命令行参数的数量,如果少于 3 个则打印错误。

static void Main(string[] args)
        {
            string file1 = args[0];
            string file2 = args[1];
            string file3 = args[2];

所以如果 args

【问题讨论】:

  • args.Length 会告诉你有多少 - 与任何其他数组相同。
  • if(ars.length

标签: c# exception command-line-arguments


【解决方案1】:

args 是一个数组——您可以访问与数组相关的所有方法。因此,您的问题的简单实现可能如下所示:

if(args.Length < 3)
     throw new ArgumentException("Must have three command line arguments");

在尝试访问变量值之前确保变量不为空几乎总是一个好主意(因此代码可能看起来像 if(args == null || args.Length &lt; 3),但根据对此答案的一些评论,这些应用程序永远不会给你args 的 null 值,因此在这种特定情况下省略它应该没问题。

【讨论】:

  • 如果发生异常,我该如何停止代码,以便其他任何东西都不会运行
  • @ben1299rogers 这个异常会导致程序停止,除非你自己捕获并处理它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 2016-05-31
  • 2020-10-11
  • 2015-05-01
  • 1970-01-01
相关资源
最近更新 更多