Vb.net “继续获取索引”超出了数组错误Visual Basic的范围

Vb.net “继续获取索引”超出了数组错误Visual Basic的范围,vb.net,visual-studio,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

在尝试运行代码时,我不断收到“索引超出数组边界”错误。它指向这条线

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
有人能帮我吗?

A不需要手动递增,循环本身为您编码:

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
如果要跳过其他所有元素,则应使用
步骤

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

旁注:我强烈建议将
选项Strict
设置为
On

您的数组是否有300个元素?@BrianMStafford是的,您使用i在for循环中,但您手动递增i。捕捉得好。我没有注意到手动增量。您是否有理由编写此代码以进行后期绑定?如果您知道传递的参数的类型,那么在方法签名中指定它。从长远来看,这将使你的生活变得简单。启用“选项严格”。