ReDim Preserve сделает это, и если массив был объявлен на уровне модуля, любой код, ссылающийся на него, не потеряет ссылку. Однако я верю, что это специфично для vb, и есть также снижение производительности, так как это также создает копию массива.
Я не проверял, но я подозреваю, что описанный выше метод user274204, вероятно, является CLR-совместимым способом сделать это. ,
Публичный класс Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Initialize your array:
Dim Integers(20) As Integer
'Output to the console, and you will see 20 elements of value 0
Me.OutputArrayValues(Integers)
'Iterate through each element and assign an integer Value:
For i = 0 To UBound(Integers)
Integers(i) = i
Next
'Output to console, and you will have values from 0 to 20:
Me.OutputArrayValues(Integers)
'Use Redim Preserve to expand the array to 30 elements:
ReDim Preserve Integers(30)
'output will show the same 0-20 values in elements 0 thru 20, and then 10 0 value elements:
Me.OutputArrayValues(Integers)
'Redim Preserve again to reduce the number of elements without data loss:
ReDim Preserve Integers(15)
'Same as above, but elements 16 thru 30 are gone:
Me.OutputArrayValues(Integers)
'This will re-initialize the array with only 5 elements, set to 0:
ReDim Integers(5)
Me.OutputArrayValues(Integers)
End Sub
Private Sub OutputArrayValues(ByVal SomeArray As Array)
For Each i As Object In SomeArray
Console.WriteLine(i)
Next
End Sub
Конечный класс