【发布时间】:2012-05-21 16:21:12
【问题描述】:
我有一个动态整数数组,我希望向其中添加新值。我该怎么做?
Dim TeamIndex(), i As Integer
For i = 0 to 100
'TeamIndex(i).Add = <some value>
Next
【问题讨论】:
我有一个动态整数数组,我希望向其中添加新值。我该怎么做?
Dim TeamIndex(), i As Integer
For i = 0 to 100
'TeamIndex(i).Add = <some value>
Next
【问题讨论】:
使用 ReDim 和 Preserve 来增加数组的大小并保留旧值。
当您不知道大小并知道要逐个增加数组大小时,建议使用循环中的 ReDim。
Dim TeamIndex(), i As Integer
For i = 0 to 100
ReDim Preserve TeamIndex(i)
TeamIndex(i) = <some value>
Next
如果您稍后在镜头中的代码中声明数组的大小,请使用
ReDim TeamIndex(100)
所以代码将是:
Dim TeamIndex(), i As Integer
ReDim TeamIndex(100)
For i = 0 to 100
TeamIndex(i) = <some value>
Next
您可以使用 ArrayList/List(Of T) 更动态地使用添加/删除值。
Sub Main()
' Create an ArrayList and add three strings to it.
Dim list As New ArrayList
list.Add("Dot")
list.Add("Net")
list.Add("Perls")
' Remove a string.
list.RemoveAt(1)
' Insert a string.
list.Insert(0, "Carrot")
' Remove a range.
list.RemoveRange(0, 2)
' Display.
Dim str As String
For Each str In list
Console.WriteLine(str)
Next
End Sub
【讨论】:
For i=0 to SomeNo。因此,如果数组将被初始化As New Integer(SomeNo),ReDim 和Preserve 在这种情况下将不需要 [Example by asker] 因为SomeNo 是常量。因此,如果SomeNo 也是可变的并且不断变化,那么ReDim 和Preserve 将是必要的!
Romil 的回答中没有什么我认为是错误的,但我会更进一步。 ReDim Preserve 是一个非常有用的命令,但重要的是要意识到它是一个昂贵的命令并明智地使用它。
考虑:
Dim TeamIndex(), i As Integer
For i = 0 to 100
ReDim Preserve TeamIndex(i)
TeamIndex(i) = <some value>
Next
对于每个循环,除了 i=0,公共语言运行时 (CLR) 必须:
ArrayList 非常棒,如果您需要从数组中间添加或删除元素,但即使您不需要它,您也需要为该功能付费。例如,如果您正在从文件中读取值并按顺序存储它们,但事先不知道会有多少值,ArrayList 会带来您可以避免的大量开销。
我总是这样使用ReDim:
Dim MyArray() As XXX
Dim InxMACrntMax As Integer
ReDim MyArray(1000)
InxMACrntMax=-1
Do While more data to add to MyArray
InxMACrntMax = InxMACrntMax + 1
If InxMACrntMax > UBound(MyArray) Then
ReDim Preserve MyArray(UBound(MyArray)+100)
End If
MyArray(InxMACrntMax) = NewValue
Loop
ReDim MyArray(InxMACrntMax) ' Discard excess elements
以上我使用了 100 和 1000。我选择的值取决于我对可能需求的评估。
【讨论】: