2016-01-27 40 views
-1

我使用C#界面概念圓& square.While給予特定條件if (args[0] == "S")面積有錯誤IndexOutOfRangeException試圖寫小程序:錯誤:指數是陣列的C#中的邊界之外

if (args[0]=="S") 
    fig = new Square(); 
if (args[0]=="C") 
    fig = new Circle(); 
+0

您不檢查args數組是否具有非零長度。如果您將代碼包含在文本中而不是鏈接到圖像,那將會更好。 –

回答

0

如果args爲空,則會發生這種情況。你不能要求空數組的第一個元素,因爲沒有一個。您應該首先檢查長度:

if (args.Length == 0) 
{ 
    // Maybe exit? Is it valid not to specify any arguments? 
} 
// Either use an "else" here, or if you've quit in the "if" block 
// then you don't need to because you know that there's at least 
// one argument by now 
相關問題