-1

我试图这样做是为了创建每个具有不同名称的对象而不定义一百个左右的名称

例如

Dim Counter as integer = 1
Public Sub Create_OBJ
    Dim Val(counter) as new rectangle(100, 100, 20, 20) 
    counter +=1 
End Sub

如果有人有任何其他建议,我会全力以赴

4

3 回答 3

3

你需要一个集合。我知道您询问过字符串,但您的示例完全基于整数。考虑到这一点, List(Of Rectangle) 似乎很合适:

'Create the base list
Dim Rectangles As New List(Of Rectangle)()

'Add a new item
Rectangles.Add(New Rectangle(100, 100, 20, 20))

'Retrieve an item by number
Dim r As Rectangle = Rectangles(0)

如果您需要索引的任意数字,而不是增量数字,您可能需要一个 Dictionary(Of Integer, Rectangle):

'Create the base dictionary
Dim Rectangles As New Dictionary(Of Integer, Rectangle)()

'Add a new item
Rectangles.Add(101, New Rectangle(100, 100, 20, 20))
'or
Rectangles(101) = New Rectangle(100, 100, 20, 20)

'Retrieve an item by number
Dim r As Rectangle = Rectangles(101)

如果您真的需要字符串,请使用 Dictionary(Of String, Rectangle):

'Create the base dictionary
Dim Rectangles As New Dictionary(Of String, Rectangle)()

'Add a new item
Rectangles.Add("101", New Rectangle(100, 100, 20, 20))
'or
Rectangles("101") = New Rectangle(100, 100, 20, 20)

'Retrieve an item by key
Dim r As Rectangle = Rectangles("101")

根据您的示例,我发现最后一个不太合适,如果您仍然认为您需要字符串,则可能值得发布一个后续问题,其中包含更详细的代码,询问最合适的代码。

于 2013-06-06T00:49:25.377 回答
1

此示例演示如何使用列表执行此操作:

Public Class Form1
    Private _listOfRectangles As New List(Of Rectangle)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' add items to the list
        _listOfRectangles.Add(New Rectangle(100, 100, 20, 20))
        _listOfRectangles.Add(New Rectangle(200, 200, 20, 20))
        _listOfRectangles.Add(New Rectangle(300, 300, 20, 20))

        Debug.Print("access an item in the list by index")
        With _listOfRectangles(0)
            Debug.Print("Top:{0} Left:{1} Height:{2} Width:{3}", .Top, .Left, .Height, .Width)
        End With

        Debug.Print("retrieve an item from the list and put it in a variable")
        Dim rzero As Rectangle = _listOfRectangles(0)
        Debug.Print("Top:{0} Left:{1} Height:{2} Width:{3}", rzero.Top, rzero.Left, rzero.Height, rzero.Width)

        Debug.Print("loop through all the rectangles")
        For Each r As Rectangle In _listOfRectangles
            Debug.Print("Top:{0} Left:{1} Height:{2} Width:{3}", r.Top, r.Left, r.Height, r.Width)
        Next
    End Sub
End Class

这是输出

access an item in the list by index
Top:100 Left:100 Height:20 Width:20
retrieve an item from the list and put it in a variable
Top:100 Left:100 Height:20 Width:20
loop through all the rectangles
Top:100 Left:100 Height:20 Width:20
Top:200 Left:200 Height:20 Width:20
Top:300 Left:300 Height:20 Width:20
于 2013-06-06T01:01:09.987 回答
0

使用字典

Dim dic as new Generic.Dictionary(of String, Rectangle)
dic("First")=New Rectangle(1,1,50,50)
dic("Second")=New Rectangle(2,2,1000,200)

Dim outDicValue as Rectangle = dic("First")
于 2013-06-06T00:49:18.117 回答