在VB.NET中搜索一个空的锯齿数组



我有一个函数查找锯齿数组中的值,它是这样的

Private Function Lookup(ByVal Search_path As String) As Integer
    Dim i As Integer = 0
    Do Until MasterIndex(i) Is Nothing 'throws an exception here
        If Search_path = MasterIndex(i)(0) Then
            Return MasterIndex(i)(1)
        End If
        i = i + 1
    Loop
    Return -1
End Function

问题是,当我用空数组测试它时,它在第3行给我Index was outside the bounds of the array的错误。我该如何解决这个问题?

您需要检查您的索引器是否超出了数组中的元素数量。

Private Function Lookup(ByVal Search_path As String) As Integer
    Dim i As Integer = 0
    Do Until i = MasterIndex.Length OrElse MasterIndex(i) Is Nothing
        If Search_path = MasterIndex(i)(0) Then
            Return MasterIndex(i)(1)
        End If
        i = i + 1
    Loop
    Return -1
End Function

可以说是FOR循环更简洁:

Private Function Lookup(ByVal Search_path As String) As Integer 
  for i = 0 to MasterIndex.Length - 1 
    if MasterIndex(i) is nothing then exit for
    If Search_path = MasterIndex(i)(0) Then 
        Return MasterIndex(i)(1) 
    End If 
  next
  Return -1 
End Function 

无休止地争议。

相关内容

  • 没有找到相关文章

最新更新