Vb.net 如何改进这个迭代函数?

Vb.net 如何改进这个迭代函数?,vb.net,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 = l

我试图简化这个函数,它类似于

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 


我不确定是否可以/如何使用控件。请在此函数中找到解决方案。有什么帮助吗?

要回答问题:

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

    If car.Visible Then
        car.Location = locate(posx(i), posy(i))
    End If
Next
可见
位置
都是
控制
类的成员,因此这些车辆变量的控制类型无关紧要

请注意,这假定所有控件都位于窗体本身上。如果它们位于不同的父容器中,则需要使用该容器的
控件
集合


另外,我已经从那里的2开始使用
I
,因此您仍然需要
car0
car1
的显式代码。如果它们始终可见,那么您可以在0处启动循环,它仍然可以工作,同时为您保存这两行代码。

winforms designer是一个陷阱,始终旨在将模型与视图分离。我们看不到car0的类型,但是猜猜看,开始用列表(PictureBox)修复这个问题。最终得到一个(汽车)列表。@HansPassant你能用外行的话解释一下我应该做什么吗?@azzamatron一个更好的设计是有一个代表你的数据的类。您可以对该类的对象进行操作,而不是直接对UI进行操作。该类可能具有窗体可以处理以更新UI的事件。这就是汉斯所指的
汽车。这种设计的答案不太适合这个网站。杰姆西林尼已经回答了你的问题。根据需要使用
Controls.Find()
(例如,如果控件位于容器中),将其与原始问题结合起来。
For i = 2 To 30
    Dim car = Controls("car" & i)

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