C# 错误:System.IndexOutOfRangeException:索引超出数组的边界
我试图使用C# 错误:System.IndexOutOfRangeException:索引超出数组的边界,c#,arrays,asp.net-mvc-4,razor,C#,Arrays,Asp.net Mvc 4,Razor,我试图使用Razor实现这个算法,但是,我得到了这个异常 System.IndexOutOfRangeException:索引超出了数组的边界 非常感谢 看来你的逻辑是错误的 如果您的选项卡[4]将是10,该怎么办?在这种情况下,您的循环将工作10次,但您的数组没有10个项。这就是为什么你可能会在你的例子tab[4]可能会比4大,这就是为什么程序尝试访问数组中没有的一些索引 数组是零索引的。定义包含5个项目的数组时,使用 int[] tab = new int[5]; 您可以访问索引为0到4的
Razor
实现这个算法,但是,我得到了这个异常
System.IndexOutOfRangeException:索引超出了数组的边界
非常感谢 看来你的逻辑是错误的 如果您的
选项卡[4]
将是10
,该怎么办?在这种情况下,您的循环将工作10次
,但您的数组没有10个
项。这就是为什么你可能会在你的例子tab[4]
可能会比4
大,这就是为什么程序尝试访问数组中没有的一些索引
数组是零索引的。定义包含5个项目的数组时,使用
int[] tab = new int[5];
您可以访问索引为0
到4
的项目
听起来你只需要像这样使用它
int[] tab = new int[5];
for (int i = 0; i < tab.Length ; i++)
{
if (tab[i] == pagination.numPageCourrante)
{
//...
}
}
int[]tab=newint[5];
for(int i=0;i
我想您不想使用数组中的值作为for循环的开始和结束。要使其正常工作,您可以执行以下任一操作:
for (int i = 0; i < tab.Length; i++)
{
var value = tab[i];
// use value ...
}
您不同的
i
值是:选项卡[0]
,选项卡[1]
,选项卡[2]
,选项卡[3]
,选项卡[4]
然后,当您调用tab[i]
时,您实际上调用了tab[tab[x]]
。x依次为0、1、2、3、4。然后,如果选项卡
的任何值不在区间[0,4]内,例如12,则尝试到达选项卡[12]
,并抛出索引自动失效异常
如果只想在数组中循环,那么错误肯定就在这里
两种正确的方法是使用for
循环:
for (int i = 0; i < tab.Length; i++)
{
// Your code here
}
foreach(int i in tab)
{
// Your code here
}
如果您这样输入…您可以在html数组中获得绑定错误: 这里的错误发生在名字上
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID"[@i], @disabled="disabled" })</td>
@Html.DropDownList(“InvoiceUnitID”+@i,新选择列表(ViewBag.UnitOfMeasures,“Value”,“Text”,“@Model.salesInvoiceVMList[i].InvoiceUnitID),htmlAttributes:new{id=“InvoiceUnitID”,name=“InvoiceUnitID”[@i],@disabled=“disabled”})
不要那样:像那样使用
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID[@i]", @disabled="disabled" })</td>
@Html.DropDownList(“InvoiceUnitID”+@i,新选择列表(ViewBag.UnitOfMeasures,“Value”,“Text”,“@Model.salesInvoiceVMList[i].InvoiceUnitID),htmlAttributes:new{id=“InvoiceUnitID”,name=“InvoiceUnitID[@i]”,@disabled=“disabled”})
选项卡数组中的值是什么?如果for循环不是for(int i=0;i Yu必须suppress=和write tab[4]+1,则该表包含5个整数的序列。根据调试器,每个单元格都有其正确的值。
foreach(int i in tab)
{
// Your code here
}
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, 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_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID[@i]", @disabled="disabled" })</td>