为什么下面的代码在 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)
为什么下面的代码在 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)
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
或者使用一些内置函数。
Dim intNum() As Integer = {1, 2, 3, 4, 5}
Dim total = intNum.Sum()