在我的Windows Forms应用程序中,在运行时每次添加一个元素时,我都需要调整数组的大小。因此,首先必须调整为
size + 1
,然后向这个索引添加一个成员。我该如何做到这一点?ReDim
语句,但这并不是最好的选择。如果您的数组大小经常会发生改变,尤其是像您所说的只是添加,那么您应该使用通用的List(Of T)
或类似的集合类型。MyList.Add(item)
要使用通用列表,请在文件顶部添加Imports System.Collections.Generics
。然后,您可以像这样声明一个新的整数列表:Dim MyList As New List(Of Integer)()
Dim MyList As New List(Of String)()
你应该明白。
ReDim Preserve MyArray(n)
Preserve
”关键字实际上并没有保留原始数组,而是分配了一个全新的数组,并逐个复制来自原始数组的元素......如果这正是你想要的,那就没问题了,但通常程序员会期望更高效的操作。 - Joel Coehoorn使用通用列表(如建议的)是最好的选择。但是,如果您想要更改数组的大小,则可以使用Array.Resize(ByRef arr, newSize)
。
ReDim不是一个好主意(VB特定的遗留问题,非常缓慢)。
Array.Resize
要比过时的 ReDim
更好。不幸的是,这两种方法可能同样缓慢。 - Ruud Helderman我建议使用某种类型的集合类,但如果您想使用数组,请按照以下方式操作:
Dim arr() As Integer
Dim cnt As Integer = 0
Dim ix As Integer
For ix = 1 To 1000
cnt = cnt + 1
ReDim arr(cnt)
arr(cnt - 1) = ix
Next
Public Class MyList
Private Items() As String
Private No As Integer = 0
Public Sub Add(ByVal NewItem As String)
''Create a temporary new string array
Dim CopyString(No) As String
''Copy values from Global Variable Items() to new CopyString array
For i As Integer = 0 To No - 1
CopyString(i) = Items(i)
Next
''Add new value - NewItem - to CopyString
CopyString(No) = NewItem
''Increment No to No + 1
No += 1
''Copy CopyString to Items
Items = CopyString
'Discard CopyString
CopyString = Nothing
End Sub
Public Sub Show(ByVal index As Integer)
MsgBox(Items(index))
End Sub
End Class
''Now create a form with a TextBox name - txt, Button1 and Button2
Public Class Form1
''Declare txts as a new MyList Class
Private txts As New MyList
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
''Add text to txts which is a MyList Class
txts.Add(txt.Text)
txt.Text = ""
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
''Display value at a specific index
txts.Show(Convert.ToInt16(txt.Text))
txt.Text = ""
End Sub
End Class
ReDim MyArray(MyArray.Length + 1)
ReDim
期望其参数为新的_上限_,而不是长度。 - Ruud Helderman正如Joel所说,使用列表。
Dim MyList As New List(Of String)
别忘了将“Of String”更改为你正在使用的任何数据类型。
这对我有效
Dim Table1 As New DataTable
' Define columns
Table1.Columns.Add("Column1", GetType(System.String))
Table1.Columns.Add("Column2", GetType(System.Int32))
Table1.Columns.Add("Column3", GetType(System.Int32))
' Add a row of data
Table1.Rows.Add("Item1", 44, 99)
Table1.Rows.Add("Item2", 42, 3)
Table1.Rows.Add("Item3", 42, 3)
Table1.Rows.Add("Item4", 42, 3)
Dim arr(-1) As String
For Each dr As DataRow In Table1.Rows
ReDim Preserve arr(arr.Length)
arr(arr.Length - 1) = dr("Column1")
Next