首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VB 2013使用循环创建100个椭圆形以模拟复杂网络

VB 2013使用循环创建100个椭圆形以模拟复杂网络
EN

Stack Overflow用户
提问于 2015-04-04 04:07:35
回答 1查看 70关注 0票数 0

我正在尝试模拟一个复杂的网络。我想用OvalShape表示100个网络节点。(我计划稍后根据网络连接算法将这些节点连接起来)我有下面的代码,它可以创建5个节点。但是,我需要创建100个节点。我能不能把它放在一个循环中,创建一个新的OvalShapes并将它们命名为theNode1,theNode2,theNode3,...theNode100?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2015-04-04 04:28:25

您可以对每个节点使用一个List,而不是为每个节点使用单独的变量:

代码语言:javascript
复制
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中的默认设置。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29438977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档