Kea*_*von 1 c# arrays for-loop indexoutofboundsexception
我有一个数组和一个for循环if语句检查i + 1.但是,在循环的最后一次迭代中,数组超出范围.当发生这种情况时,我想循环回到数组的开头.循环回来的最佳方式是什么array[0]?这是我的代码:
int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);
for (int i = 0; i < array.Length; i++)
{
if (array[i + 1] != 0)
// Do something (obviously in this example, this will always occur)
{
}
Run Code Online (Sandbox Code Playgroud)
我可以执行以下操作,但它需要我复制我的代码(我当前的代码是巨大的).有没有更好的方法来做到以下几点?
int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);
for (int i = 0; i < array.Length; i++)
{
if (i != array.Length - 1)
{
if (array[i + 1] != 0)
// Do something (obviously in this example, this will always occur)
{
}
else
{
if (array[0] != 0)
// Do something (obviously in this example, this will always occur)
{
}
}
Run Code Online (Sandbox Code Playgroud)
使用模数:
if(array[(i+1) % array.Length] != 0) {...}
Run Code Online (Sandbox Code Playgroud)
这将基本上从(i + 1)减去array.Length直到(i + 1)<array.Length
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |