2011-01-26 59 views
2

可以說,我想創建一個所有設置爲默認值20個元素的數組(比方說,0)創建陣列和調整他們

但後來,在運行時,我可能要調整大小的數組。我可能會擴大它,以支持30個元素。這10個新元素的默認值爲0.

或者我可能想讓我的數組更小,只是5.因此,我刪除了數組中最後15個元素的完整存在。

謝謝。

回答

2

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 

末級

+0

什麼貌似很多的代碼只是一堆意見解釋發生了什麼。 – XIVSolutions 2011-01-26 05:32:24

0

一旦創建,就不可能調整數組的大小(或任何其他對象)。

您可以使用System.Array.Resize(ref T [],int)獲得類似的效果。然而,這實際上會創建一個新的數組,並將相關部分複製到一起,如果多次引用散佈的數組,則可能不是您想要的。