为什么下面的代码在运行时给出了一个空引用异常?(假设在窗体打开时计时器开始计时)。我将在许多sub中使用该数组,并且我不想在每个子语句中声明数组,以便它们可以工作,因为它使程序很长。
注意: 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 :(得分: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