C#索引在列表中数组的边界之外

时间:2012-08-06 13:33:57

标签: c# indexing bounds

我有以下代码:

 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](在这种情况下)是null,但它不是

提前致谢!

2 个答案:

答案 0 :(得分:4)

我在这里看到了几个可能的问题:

  1. 如果arg[]为空,您将获得例外
  2. 如果arg[j]为空字符串,则会出现异常
  3. 如果您有任何选项,您将在稍后执行循环时获得异常,因为j正在递增,但i未递增。
  4. 我认为这会解决它:

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

答案 1 :(得分:2)

当你尝试索引没有元素的元素时会得到这个,例如,通常你在数组小于预期时索引元素。

在您的情况下,要么:

  • j的值大于或等于arg.Length,因此arg[j]会超出范围。
  • arg[j]中的字符串没有字符,因此arg[j][0]抛出了界限。

您可以使用数组的Length属性测试长度。 string也有Length属性。

除此之外,在所有情况下,您都不会增加j,除了支票之外,您似乎甚至不会使用i,{{1}可能比j进一步递增,这意味着您i不会对while (i != args.Length)进行辩护。此外,检查至少IndexOutOfBoundsException