遍历数组而不会引发异常 [英] Looping through an array without throwing exception
本文介绍了遍历数组而不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个值数组:
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
然后我有一个基本的循环:
Then I have a basic loop:
for (int i = 0; i <= 30; i++)
{
Console.WriteLine(i + " = " + text[i])
}
很明显,这将导致超出范围的异常,所以我想做的是当计数器达到数组的上限然后回到起点.
Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start.
所以
0 = val1
1 = val2
2 = val3
3 = val4
4 = val5
5 = val1
6 = val2
7 = val3
etc..
推荐答案
您可以使用模运算符:
Console.WriteLine(i + " = " + text[i % 5])
这篇关于遍历数组而不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文