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

时间:2011-10-17 13:15:42

标签: vb.net function loops jagged-arrays

所以我有一个在锯齿状数组中查找值的函数,它是这样的:

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的错误。如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

可以说是更清洁的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 

无休止地争论。