-6

为什么下面的代码在 VB.Net 中会给出 IndexOutOfRangeException:

    Dim intNum() As Integer = {1, 2, 3, 4, 5}
    Dim tot As Integer
    For Each n As Integer In intNum
        tot = tot + intNum(n)
    Next
    MsgBox(tot)
4

2 回答 2

3

Assuming you mean VB.NET, array indices range from 0 to the array upper bound of 4 which you exceed at the last index. If you wish to sum the elements you could do

For Each n As Integer In intNum
    tot = tot + n
Next
于 2015-08-01T01:43:38.433 回答
2

或者使用一些内置函数。

Dim intNum() As Integer = {1, 2, 3, 4, 5}
Dim total = intNum.Sum()
于 2015-08-01T02:03:57.003 回答