我正在尝试模拟一个复杂的网络。我想用OvalShape表示100个网络节点。(我计划稍后根据网络连接算法将这些节点连接起来)我有下面的代码,它可以创建5个节点。但是,我需要创建100个节点。我能不能把它放在一个循环中,创建一个新的OvalShapes并将它们命名为theNode1,theNode2,theNode3,...theNode100?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim canvas As New ShapeContainer
' Set the form as the parent of the ShapeContainer.
canvas.Parent = Me
Dim theNode1 As New OvalShape
Dim theNode2 As New OvalShape
Dim theNode3 As New OvalShape
Dim theNode4 As New OvalShape
Dim theNode5 As New OvalShape
' Set the ShapeContainer as the parent of the OvalShape.
theNode1.Parent = canvas
theNode2.Parent = canvas
theNode3.Parent = canvas
theNode4.Parent = canvas
theNode5.Parent = canvas
theNode1.SetBounds(100, 100, 50, 50)
theNode2.SetBounds(100, 200, 50, 50)
theNode3.SetBounds(100, 100, 50, 50)
theNode4.SetBounds(200, 200, 50, 50)
theNode5.SetBounds(200, 100, 50, 50)
End Sub发布于 2015-04-04 04:28:25
您可以对每个节点使用一个List,而不是为每个节点使用单独的变量:
Private Sub CreateOvals()
Dim canvas As New ShapeContainer
' Set the form as the parent of the ShapeContainer.
canvas.parent = Me
Dim nodes As New List(Of OvalShape)
' create 5 nodes and set the .parent for each one
For i = 0 To 4
nodes.Add(New OvalShape With {.parent = canvas})
Next
' call SetBounds as required
nodes(0).SetBounds(100, 100, 50, 50)
nodes(1).SetBounds(100, 200, 50, 50)
nodes(2).SetBounds(100, 100, 50, 50)
nodes(3).SetBounds(200, 200, 50, 50)
nodes(4).SetBounds(200, 100, 50, 50)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CreateOvals()
End Sub从Form1_Load处理程序中调用单独的Subs通常更好-这使得修改特定部分变得更容易,而不会陷入试图弄清楚哪个部分做什么的泥潭,并且为方法使用有意义的名称使其更具可读性。
此外,如果您还没有发现它,我强烈建议使用Option Strict On -并将其设置为Visual Studio中的默认设置。
https://stackoverflow.com/questions/29438977
复制相似问题