继续获得索引超出了数组错误Visual Basic的范围

时间:2018-02-22 14:31:16

标签: vb.net visual-studio

我不断得到一个"索引超出了数组的范围"尝试运行我的代码时出错。它指向这一行。

If order(i).purchaseMethod = "S" Then

正是在这种情况下

Sub calculatePopularPayment(ByRef popularMethod, ByVal order)
    'declares the subclass-specific variables
    Dim i As Integer = 0
    Dim officeCount As Integer = 0
    Dim websiteCount As Integer = 0

    For i = 0 To 299
        If order(i).purchaseMethod = "S" Then
            officeCount = officeCount + 1
        ElseIf order(i).purchaseMethod = "W" Then
            websiteCount = websiteCount + 1
        End If
        i = i + 1
    Next

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

不需要手动递增For-loop,循环本身就为你增加了它:

For i = 0 To 299
    If order(i).purchaseMethod = "S" Then
        officeCount = officeCount + 1
    ElseIf order(i).purchaseMethod = "W" Then
        websiteCount = websiteCount + 1
    End If
Next

当然,如果数组中的项目少于300个,这仍会抛出此异常。如果要迭代所有应使用的项目:

For i = 0 To order.Length - 1
  ...
Next

如果您想跳过其他所有元素,请使用Step

For i = 0 To 299 Step 2
   ....
Next

附注:我强烈建议您将Option Strict设为On