【问题标题】:The proper way to use parameters/arguments in c#?在 c# 中使用参数/参数的正确方法?
【发布时间】:2014-02-24 15:14:09
【问题描述】:

我有一个应用程序,它获取 3 个主要参数:求和、减法、打印。如果给定了其中一个参数,应用程序将调用方法:sum 为 sum,substract 为 substract,print 为 print。

带参数调用所有例子:

myapp.exe sum 1 2
myapp.exe substract 3
myapp.exe print whatever

这是我的实际代码,它不起作用

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

        if (args[0] == @"sum")
        {

            package.sum(args[1], args[2]);
        }

        else if (args[0] == @"substract")
        {
            package.substract(args[1]);
        }

        else if (args[0] == @"print")
        {
            package.print(args[1]);
        }

        else
            Console.Write("Invalid Parameters");
    }

但这是我调试时遇到的错误:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in myapp.exe
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in myapp.exe
Additional information: Index was outside the bounds of the array.

我做错了什么?使用参数的最佳方式是什么?

【问题讨论】:

  • 单步调试您的代码。
  • 代码看起来OK,调试的时候在哪里提供参数(参数)?
  • 看看 Giacomo Stelluti Scala 的 Command Line Parser commandline.codeplex.com/documentation

标签: c# parameters arguments


【解决方案1】:

我做错了什么?

您假设始终使用适当数量的参数调用程序。具体来说,

  • 至少存在一个参数
  • 当初始参数为sumprint时,存在两个参数
  • 当初始参数为add时,存在三个参数

这并不总是正确的,这取决于用户输入的内容。您需要在引用其元素之前添加代码检查 args 数组的长度:

if (args.Length < 2) {
    Console.Error.Write("Invalid Parameters");
    return;
}
if (args[0] == @"sum" && args.Length == 3) {
    ...
}
... // The rest of your code can assume that there's at least two args

【讨论】:

    【解决方案2】:

    上面的答案很好,但我觉得这个答案不仅仅是变量的数量。

    我发现以下类型的解决方案最适合我在需要某种稳健的论证解决方案时:

    if (args.Length > 0)
    {
        if (args.Contains<string>("--help"))
        {
            Console.WriteLine("appname [--debug] [--bootstrap <bootstrap name>]");
            Console.WriteLine(" --debug       Runs \"appname\" in debug mode.")
            Console.WriteLine(" --bootstrap   If no bootstrap name is provided the default \"AppName v1.2\" will be used.")
            Console.WriteLine("")
        }
        //simple single argument passed to application
        if (args.Contains<string>("--debug")) 
        {
            DEBUG_ON = true;
            Console.WriteLine("Found argument: --debug");
        }
        //more complex relational argument passed to application
        if (args.Contains<string>("--bootstrap")) 
        {
            int bootstrapLoc = Array.IndexOf<string>(args, "--bootstrap");
            //always check that there is one more argument in the array
            if(args.Length > bootstrapLoc + 1)
            {
                string bootstrapArg = args[bootstrapLoc + 1];
                //this is where you would do your error checking against the second argument, ex: determine that it is what is expected
                if (bootstrapArg != null && bootstrapArg != "")
                {
                    this.MongoDBInstallName = bootstrapArg;
                    Console.WriteLine("Using the passed bootstrap arg: " + bootstrapArg);
                }
            }
        }
    }
    

    肯定有更好的方法可以做到这一点,这绝不是万无一失的,但我只是想为这个问题添加更多细节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多