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])