简体   繁体   English

Visual Basic:图片框数组的声明

[英]Visual Basic: Declaration of Array of Pictureboxes

Why is that the code below gives a null reference exception at runtime?(assuming that the timer starts ticking when the form opens). 为什么下面的代码在运行时给出空引用异常?(假设计时器在窗体打开时开始计时)。 I'm gonna use the array in many sub and I don't want to declare the array in each subs for them to work if it is possible because it makes the programs very long. 我要在许多子程序中使用该数组,如果可能的话,我不想在每个子程序中声明该数组以使其工作,因为这会使程序变得很长。

NOTE: Pictureboxes Enemy1_1, Enemy1_2, Enemy1_3 and so on are already on the form from the start. 注意:图片框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

Maybe you were looking for something more sophisticated than the below, LOL... but at least it will probably stop the page from bombing out, and/or confirm where the exception is happening: 也许您在寻找比下面更复杂的东西,哈哈...但是至少它可能会阻止页面轰炸,和/或确认发生异常的地方

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM