2014-02-24 55 views
1

我有一個應用程序,獲取3個主要參數:sum,substract,print。如果給出了這些參數之一,則應用程序會調用方法:求和的總和,減去的減去量,打印的打印量。在c#中使用參數/參數的正確方法?

用的參數調用所有的例子:

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. 

我在做什麼錯?使用參數的最佳方式是什麼?

+0

逐步通過您的代碼。 – tnw

+0

代碼看起來不錯,您在調試時從哪裏提供參數(參數)? –

+0

看看Giacomo Stelluti Scala的命令行解析器http://commandline.codeplex.com/documentation。 – Xaruth

回答

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 
+0

謝謝,我會試試這個 –

1

以上回答是不錯,但我覺得還有更多的這個答案比的變量只是數量一點點。

我發現以下類型的解決方案最適合我的需要稍微強大的參數解決方案時:

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

肯定有更好的方法絕不是要做到這一點,這是愚蠢的證明,但我只是想爲這個問題添加更多的細節。

相關問題