如何改善此迭代功能?

时间:2020-03-16 22:03:31

标签: vb.net

我正在尝试简化与

类似的功能
Function Snake_makestep()
        maincar.Location = locate(xpos, ypos)
        car0.Location = locate(posx(0), posy(0))
        car1.Location = locate(posx(1), posy(1))
        If car2.Visible = True Then
            car2.Location = locate(posx(2), posy(2))
        End If
        If car3.Visible = True Then
            car3.Location = locate(posx(3), posy(3))
        End If
        If car4.Visible = True Then
            car4.Location = locate(posx(4), posy(4))
        End If 

收件人

If car30.Visible = True Then
            car30.Location = locate(posx(30), posy(30))
        End If
    End Function

我不确定是否可以/如何使用Controls.Find解决方案。有帮助吗?

1 个答案:

答案 0 :(得分:0)

要回答以下问题:

For i = 2 To 30
    Dim car = Controls("car" & i)

    If car.Visible Then
        car.Location = locate(posx(i), posy(i))
    End If
Next

VisibleLocation都是Control类的成员,所以这些 car 变量是什么类型的控件都没有关系。

请注意,这假定所有控件都在表单本身上。如果它们在另一个父容器中,则需要使用该容器的Controls集合。

此外,我从i的2开始,所以您仍然需要car0car1的显式代码。如果它们始终可见,那么您可以从0开始循环,它仍然可以正常工作,并保存这两行代码。