对于Visual Basic中的每个循环:IndexOutOfRangeException

时间:2015-08-01 01:30:29

标签: .net vb.net indexoutofrangeexception

为什么下面的代码在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)

2 个答案:

答案 0 :(得分:3)

假设您的意思是VB.NET,数组索引的范围从0到最后一个索引处超过的数组上限4。如果你想总结你可以做的元素

For Each n As Integer In intNum
    tot = tot + n
Next

答案 1 :(得分:2)

或使用一些内置功能。<​​/ p>

Dim intNum() As Integer = {1, 2, 3, 4, 5}
Dim total = intNum.Sum()