winforms 如何创建一个PictureBox数组并使用它?

up9lanfz  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(139)

我认为"brickn()"将创建一个数组,"NoOfBrick"将是数组长度,所有数组都将存储在其中

Dim brickWidth as Integer = 0
Dim Brickn() As PictureBox  
dim NoOfBrick as Integer       ' array length

Public Function CreateBrick() As PictureBox
  Dim myBrickn As New PictureBox

  With myBrickn
    .Size = Brick.Size
    .Left = BrickWidth
    .Top = 0
    .Image = Brick.Image
    .SizeMode = PictureBoxSizeMode.StretchImage
    .BackColor = Color.Black
  End With

  Return myBrickn
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
   For i = -75 To Me.Width 
     Brickn(NoOfBrick) = CreateBrick() 'and also how to add array/list here 
     Me.Controls.Add(Brickn(NoOfBrick))
     BrickWidth += 170 'increasing brick.left on every new brick is created 
     i += 170          ' increasing looop count according to brick needed    
     NoOfBrick +=1
  Next
End Sub

但是这段代码在"Me.Controls.Add(Brickn(NoOfBrick))"上抛出错误
System.NullReferenceException: '对象引用未设置为对象的示例。'
我想,如果我将获得PictureBox数组,那么我可以访问控制他们的这一点

Private Sub Boll_control_Tick(sender As Object, e As EventArgs) Handles Boll_control.Tick
  If Ball.Bounds.IntersectsWith(brickn(NoOfBrick).Bounds) Then
    Me.Controls.Remove(brickn(NoOfBrick))
  End If
End Sub
vmjh9lq9

vmjh9lq91#

变更:

Dim Brickn() As PictureBox

收件人:

Dim Brickn As New List(Of PictureBox)

然后,当你想Add某事到“Brickn”,你会做:

Brickn.Add(CreateBrick())

您仍然可以使用数组语法访问“Brickn”,例如:

Brickn(NoOfBrick).Bounds

不同之处在于,List的大小会随着您向其中添加/删除内容而自动增长或收缩,而Array的大小是固定的(您从未在代码中实际创建数组并为其指定大小)。
您可以使用以下方法进行命中测试:

Dim hit = Brickn.Where(Function(brick) Ball.Bounds.IntersectsWith(brick.Bounds))
For Each brick As PictureBox In hit
    Me.Controls.Remove(brick)
    Brickn.Remove(brick)
Next

相关问题