1

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

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

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

4

2 回答 2

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
于 2011-10-17T13:44:13.717 回答
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 

争论不休。

于 2011-10-17T15:05:28.823 回答