2012-08-06 18 views
0

我有以下代碼:C#指數

public List<IAction> Dispatch(string[] arg) 
    { 
     int time=0; 
     int i = 0; 
     int j = 0; 
     List<IAction> t = new List<IAction>(10); 
     do 
     { 
      if (arg[j][0] == '/') // I get index out of bounds here 
      { 
       Options opt = new Options();     

       time = opt.Option(arg[j]); 
       j++; 
      } 
      else 
      { 
       if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20) 
       { 
        t.Add(new ComputeParam(int.Parse(arg[j]))); 
        i++; 
        j++;      
       } 
      } 

     } while (i != arg.Length); 
     for (int z = 0; z < t.Count; z++) 
     { 
      ((ComputeParam)t[z]).Time = time; 
     } 
     return t; 
    } 

爲什麼錯誤發生...我只是傳遞參數,如果他們是數字我將它們添加到一個列表,如果沒有,我設置一個選項,繼續前進。這裏有什麼問題?

編輯:我通過2/t:Med 2 3 這些是論據。我已經檢查它arg [1](在這種情況下)是空的,但它不是

在此先感謝!

+5

'arg'爲空或'ARG [J]字符串'沒有字符。你不能索引不存在的東西。 – 2012-08-06 13:35:47

+0

如果沒有參數通過,該怎麼辦? – nothrow 2012-08-06 13:35:48

+0

你有沒有在這裏放置一個斷點? ARG [j]的[0]。此時參數的值是多少 – 2012-08-06 13:35:52

回答

4

我看到一對夫婦的可能的問題在這裏:

  1. 如果arg[]是空的,你會得到異常
  2. 如果arg[j]是一個空字符串,您將獲得例外
  3. 如果您有任何選項,您將在稍後執行循環時收到異常,因爲j正在增加,但i不是。

我認爲這將解決這個問題:

public List<IAction> Dispatch(string[] arg) 
{ 
    int time=0; 
    List<IAction> t = new List<IAction>(10); 
    for (int j = 0; j < arg.Length; j++) 
    { 
     if (!String.IsNullOrEmpty(arg[j]) && arg[j][0] == '/') 
     { 
      Options opt = new Options();     

      time = opt.Option(arg[j]); 
     } 
     else 
     { 
      if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20) 
      { 
       t.Add(new ComputeParam(int.Parse(arg[j]))); 
       // Don't need to increment i     
      } 
     } 

    } 
    for (int z = 0; z < t.Count; z++) 
    { 
     ((ComputeParam)t[z]).Time = time; 
    } 
    return t; 
} 
+0

現在我只是覺得很傻。我用我而不是j。感謝您的幫助 – robertpas 2012-08-06 13:49:55

+0

哈哈,沒問題。是星期一。 :) – 2012-08-06 13:50:27

+1

+1因爲煩擾修理它大聲笑 – 2012-08-06 13:50:43

2

當你嘗試索引一個沒有元素的元素時,你會得到這個,比如,當數組比你所期望的要小時,你通常會索引元素。

在你的情況,或者:

  • j的值大於或等於arg.Length所以arg[j]拋出出界。
  • arg[j]中的字符串沒有字符,所以arg[j][0]拋出界限。

您可以使用數組的Length屬性測試長度。 string也有一個Length屬性。

正如順便說一句,你不增加在所有情況下j,你甚至不似乎使用i以外的檢查,但j可能已超過i進一步增加意味着你的while (i != args.Length)不會防守你反對IndexOutOfBoundsException。此外,檢查應至少while (i < args.Length)