2010-11-29 47 views
-2

在線路`如果aryTemp(1)< aryTemp2(1)然後,將VB.Net的NullReferenceException

指數是 陣列的邊界之外。

出現錯誤。無法弄清楚它爲什麼會超出數組的界限。 基本上試圖比較姓氏排序記錄並將em放回到列表框中。

Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click 
     'load all students into array 
     Dim arySort(numberOfRecords) As String 
     Dim aryTemp(6) As String 
     Dim aryTemp2(6) As String 
     For i = 0 To numberOfRecords - 1 
      arySort(i) = lstListBox.Items(i) 
     Next 
     Dim temp As String 'holds temporary record 
     Dim k As Integer 
     For i = 0 To arySort.Length - 2 
      aryTemp = Split(arySort(i), " ") 
      For k = i + 1 To arySort.Length - 1 
       aryTemp2 = Split(arySort(k), " ") 
       If aryTemp(1) < aryTemp2(1) Then 
        temp = arySort(k) 
        arySort(k) = arySort(i) 
        arySort(i) = temp 
       End If 
      Next 
     Next 
     lstListBox.Items.Clear() 
     numberOfRecords = 0 
     isLoaded = False 
     For i = 0 To arySort.Length - 1 
      lstListBox.Items.Add(arySort(i)) 
      numberOfRecords += 1 
     Next 
     currentRecord = 0 
     isLoaded = True 
    End Sub 
+0

你的代碼在哪裏拋出更精確? – 2010-11-29 23:45:18

+0

既然你什麼時候可以在沒有`New`關鍵字的情況下在VB.NET中分配一個數組呢?是不是正確的語法Dim aryTemp as New String(6)`,還是我在這裏丟失了什麼? – ja72 2010-11-29 23:55:21

回答

1

好,無論是arySortlstListBoxNothing但沒有更多的代碼,我不能告訴。調試器可能會有所幫助。

+0

明白了。新問題發佈而不是原始問題。 – JohnnyCake 2010-11-29 20:40:21

0

A NullReferenceException這麼說。

當試圖取消引用空對象引用時引發的異常。

這意味着您正試圖訪問實際尚未分配值的變量,或者指定了Nothing值。在類對象的情況下,這意味着你的對象沒有被實例化。

在你的ListBox的情況下,它需要實例化,如果它是Nothing;

在你的數組arySort的情況下,你是否初始化它,或者它仍然是Nothing

當你面對這樣一個NullReferenceException,問問自己是否有所有預期的初始化和實例化。當一個變量不是Nothing時,問問自己爲什麼會這樣。對自己的這種懷疑很可能會引導您解決正確的問題。

另一個好的做法是在嘗試訪問變量之前驗證變量是否爲Nothing

EDIT#1

指數陣列的邊界之外。

這是一個IndexOutOfRangeException

當嘗試訪問數組的元素並且索引超出數組邊界時引發的異常。這個類不能被繼承。

每當嘗試訪問實際超出其長度的數組索引時,都會引發此異常。

object[] objects = new object() { 1, 2, 3 }; 

for (int index = 0; index <= objects.Length; index++) { 
    // The following line will throw an `IndexOutOfRangeException` when index = objects.Length 
    Console.WriteLine(objects[index].ToString());  
} 

因爲。.NET數組和集合是基於零的,也就是說,數組或集合的第一個索引是0,試圖訪問一個值得數組長度的索引可能會導致它出界。實際上,對象數組的長度爲3.另外,訪問objects[3]會拋出,因爲3是它的長度,而不是它的上限。

這就是說:

objects[0]; // This will return the object value of 1, the first value placed in the array. 
objects[1]; // This will return the object value of 2, the second value placed in the array. 
objects[2]; // This will return the object value of 3, the thrid value placed in the array. 
objects[3]; // Throws the `IndexOutOfRangeException` here, 
      // as there is no value stored at this index, hance this index doesn't even exist 
      // in the array! 

概括起來講,你總要考慮一個從零開始的索引,也就是數組的長度 - 1

for (int index = 0; index < objects.Length; i++) 
    Console.WrilteLine(object[index]); 

哪個輸出將是:

1 
2 
3