2014-01-30 67 views
1

我试图实现使用Razor该算法的范围之外,但是,我得到这个例外错误:System.IndexOutOfRangeException:索引数组

System.IndexOutOfRangeException:索引已超出界限的的阵列。

@{ 
//.... 
for (int i = tab[0]; i <= tab[4]; i++) 
     { 
      if (i == pagination.numPageCourrante) 
      { 
       <li class="active"><a href="#">@i <span class="sr-only">(current)</span></a></li> 
      } 
      else 
      {//from here the exception triggers 
       <li><a href="/Accueil/Rechercher?rech=micro&type=nomAppMetier&[email protected](tab[i])">@i </a></li> 
      } 

     } 

} 

知道该表的声明是:

int[] tab = new int[5]; 

非常感谢!

+0

什么是你的标签数组中值是多少?如果您的for循环不是for(int i = 0; i <= 4 ...)通过执行tab [0]和tab [4],您正在使用这些索引处的值。 – David

+0

标签[4]是什么? – RononDex

+0

Yu必须supress =和写选项卡[4] +1 –

回答

2

似乎你的逻辑错误。

如果您的tab[4]将是10会怎么样?在这种情况下,您的循环将工作10次,但您的阵列没有10项。这就是为什么你可能在你的例子中得到IndexOutOfRangeExceptiontab[4]可能会大于4,这就是为什么您的程序尝试访问您的数组没有的索引

数组是零索引的。当你用5个项目定义一个数组时;

int[] tab = new int[5]; 

您可以访问项目索引04

听起来像你只需要使用它像;

int[] tab = new int[5]; 
for (int i = 0; i < tab.Length ; i++) 
{ 
    if (tab[i] == pagination.numPageCourrante) 
    { 
     //... 
    } 
} 
0

我想你不想使用数组中的值作为for循环的开始和结束。为了使其工作,您可以执行下列操作:

for (int i = 0; i < tab.Length; i++) 
{ 
    var value = tab[i]; 
    // use value ... 
} 

或者,你也可以使用的foreach:

foreach(int value in tab) 
{ 
    // use value ... 
} 
0

你不同i值是:tab[0]tab[1]tab[2]tab[3]tab[4]

然后当你拨打tab[i]你实际上叫tab[tab[x]]。 x依次为0,1,2,3,4。然后,如果您的任何tab值不在间隔[0,4]中,例如12,则尝试达到tab[12],并且IndexOutOFRangeException被抛出。

这肯定是错误的地方,如果你想简单地遍历你的数组。

两个正确的方式做到这一点是有for循环:

for (int i = 0; i < tab.Length; i++) 
{ 
    // Your code here 
} 

或用foreach循环:

foreach(int i in tab) 
{ 
    // Your code here 
} 
0

如果u进入这样的...ü可以得到HTML阵列绑定错误:

在这里的名字

<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"[email protected], new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID"[@i], @disabled="disabled" })</td> 

,而不是所发生的错误:使用这样的

<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"[email protected], new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID[@i]", @disabled="disabled" })</td>