0

为什么下面的代码会在运行时给出空引用异常?(假设计时器在表单打开时开始计时)。我将在许多子程序中使用该数组,如果可能的话,我不想在每个子程序中声明该数组以便它们工作,因为它会使程序很长。

注意:图片框 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
4

1 回答 1

0

也许您正在寻找比下面更复杂的东西,哈哈......但至少它可能会阻止页面轰炸,和/或确认发生异常的位置:

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
于 2013-10-12T15:44:28.303 回答