2015-04-03 42 views
0

我想模拟一个复杂的网络。我想用OvalShape代表100个网络节点。 (我打算以后根据网络连接alogirthm连接这些线)我有下面的代码创建5个节点就好了。但是,我需要制作100个节点。我可以以某种方式将它放入循环中以创建新的OvalShapes并将它们命名为节点1,节点2,节点3,... theNode100?VB 2013使用循环模拟复杂网络创建100个椭圆形

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 

回答

0

而不是使用一个单独的变量为每个节点的,你可以让他们的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的处理程序调用单独的替补 - 这使得它更容易修改一个特定的部分而不会陷入困境,试图找出哪个部分做了什么,并使用有意义的方法名称使其更具可读性。另外,如果您还没有发现它,我强烈建议您使用Option Strict On - 并将其设置为Visual Studio中的默认设置。