从图像列表中将图像分配给图片框

Assigning images to a picturebox from an imagelist

我必须将数组中随机分配的 16 张图像分配给图片框。我想出了创建图像列表然后将它们分配给图片框的想法。 有没有办法缩短这个? 这是我想出的代码:

For i = 0 To FotoArray.Length - 1
                ImageList1.Images.Add(Image.FromFile(FotoArray(i)))
            Next
    
            PictureBox1.Image = ImageList1.Images(0)
        PictureBox2.Image = ImageList1.Images(1)
        PictureBox3.Image = ImageList1.Images(2)
        PictureBox4.Image = ImageList1.Images(3)
        PictureBox5.Image = ImageList1.Images(4)
        PictureBox6.Image = ImageList1.Images(5)
        PictureBox7.Image = ImageList1.Images(6)
        PictureBox8.Image = ImageList1.Images(7)
        PictureBox9.Image = ImageList1.Images(8)
        PictureBox10.Image = ImageList1.Images(9)
        PictureBox11.Image = ImageList1.Images(10)
        PictureBox12.Image = ImageList1.Images(11)
        PictureBox13.Image = ImageList1.Images(12)
        PictureBox14.Image = ImageList1.Images(13)
        PictureBox15.Image = ImageList1.Images(14)
        PictureBox16.Image = ImageList1.Images(15)

还有这个

有没有办法为这个标签做同样的事情?

Label1.Tag = FotoArray(0)
Label2.Tag = FotoArray(1)
Label3.Tag = FotoArray(2)
Label4.Tag = FotoArray(3)
Label5.Tag = FotoArray(4)
Label6.Tag = FotoArray(5)
Label7.Tag = FotoArray(6)
Label8.Tag = FotoArray(7)
Label9.Tag = FotoArray(8)
Label10.Tag = FotoArray(9)
Label11.Tag = FotoArray(10)
Label12.Tag = FotoArray(11)
Label16.Tag = FotoArray(12)
Label13.Tag = FotoArray(13)
Label15.Tag = FotoArray(14)
Label14.Tag = FotoArray(15)

您可以使用 OfType Linq extension method 来帮助简化此代码,例如:

    Dim pictureBoxes As List(Of PictureBox) = Me.Controls.OfType(Of PictureBox).ToList()

    For counter As Integer = 0 To pictureBoxes.Count - 1
        Dim pb As PictureBox = pictureBoxes(counter)
        pb.Image = ImageList1.Images(counter)
    Next

来自 MSDN:

Filters the elements of an IEnumerable based on a specified type.