2013-08-28 69 views
0

爲什麼下面的代碼在運行時給出空引用異常?(假定計時器在窗體打開時開始計時)。我將在很多sub中使用數組,並且我不想在每個subs中聲明數組,以便它們可以工作,因爲它會使程序變得很長。Visual Basic:聲明數組的圖片框

注意: Pictureboxes Enemy1_1,Enemy1_2,Enemy1_3等已經從表格開始。

Public Class Form1 
    Dim Array1() As PictureBox = {Enemy1_1, Enemy1_2, Enemy1_3} 
    Dim Array2() As PictureBox = {Enemy2_1, Enemy2_2, Enemy2_3} 
    Dim Array3() As PictureBox = {Enemy3_1, Enemy3_2, Enemy3_3} 

    Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick 
     For index As Integer = 0 To 2 
      Array1(index).Left += 5 
      Array2(index).Left += 5 
      Array3(index).Left += 5 
     Next 
    End Sub 
End Class 
+0

您是否創建了9個圖片框(_EnemyX_Y_)?不調用_EnemyX_Y = new PictureBox()_ NullReference異常有保證 – Steve

+0

pictureboxex EnemyX_Y已經從表單開始創建。我只使用Array1,Array2和Array3來更容易地訪問picturebox。 – shriekyphantom

+0

我只能建議在定時器函數中放置一個斷點,並檢查ArrayX(index)是否指向一個有效的PictureBox(非null) – Steve

回答

0

也許你要找的東西比下面更復雜的,LOL ...... 但至少它可能會從炸出來, 停止頁面和/或確認其中的例外是發生的事情:

Public Class Form1 
    Dim Array1() As PictureBox = {Enemy1_1, Enemy1_2, Enemy1_3} 
    Dim Array2() As PictureBox = {Enemy2_1, Enemy2_2, Enemy2_3} 
    Dim Array3() As PictureBox = {Enemy3_1, Enemy3_2, Enemy3_3} 

    Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick 
     For index As Integer = 0 To 2 
      If Array1(index) IsNot Nothing Then 
       Array1(index).Left += 5 
      End If 
      If Array2(index) IsNot Nothing Then 
       Array2(index).Left += 5 
      End If 
      If Array3(index) IsNot Nothing Then 
       Array3(index).Left += 5 
      End If 
     Next 
    End Sub 
End Class