C#通过数组循环没有抛出异常 [英] C# Looping through an array without throwing exception
本文介绍了C#通过数组循环没有抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有值的数组:
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
等
推荐答案
您可以使用模运算符:
Console.WriteLine(i + " = " + text[i % 5])
这篇关于C#通过数组循环没有抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文