我试图这样做是为了创建每个具有不同名称的对象而不定义一百个左右的名称
例如
Dim Counter as integer = 1
Public Sub Create_OBJ
Dim Val(counter) as new rectangle(100, 100, 20, 20)
counter +=1
End Sub
如果有人有任何其他建议我都是耳朵
答案 0 :(得分: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")
根据你的例子,我发现这最后一个是不合适的,如果你仍然认为你想要字符串,可能值得发布一个后续问题,更详细的代码询问什么是最合适的。
答案 1 :(得分: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
答案 2 :(得分: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")