Vb.net 创建数组并调整其大小
假设我想创建一个数组,其中20个元素都设置为默认值(假设为0) 但稍后,在运行时,我可能希望调整数组的大小。我可以把它放大,支持30个元素。10个新元素的默认值为0 或者我可能想把我的数组缩小到5个。所以我删除了数组最后15个元素的完整存在性Vb.net 创建数组并调整其大小,vb.net,arrays,resize,elements,Vb.net,Arrays,Resize,Elements,假设我想创建一个数组,其中20个元素都设置为默认值(假设为0) 但稍后,在运行时,我可能希望调整数组的大小。我可以把它放大,支持30个元素。10个新元素的默认值为0 或者我可能想把我的数组缩小到5个。所以我删除了数组最后15个元素的完整存在性 谢谢。一经创建,就无法调整数组(或任何其他对象)的大小 您可以使用System.Array.Resize(ref T[],int)获得类似的效果。但是,这实际上会创建一个新阵列,并将相关部分复制到各个阵列上,如果有多个对阵列的引用分散在各个阵列上,这可能不
谢谢。一经创建,就无法调整数组(或任何其他对象)的大小
您可以使用System.Array.Resize(ref T[],int)获得类似的效果。但是,这实际上会创建一个新阵列,并将相关部分复制到各个阵列上,如果有多个对阵列的引用分散在各个阵列上,这可能不是您想要的。ReDim Preserve将执行此操作,并且如果阵列是在模块级别声明的,任何引用它的代码都不会丢失引用。不过,我确实认为这是vb特有的,而且还有一个性能损失,因为这也会创建数组的副本 我还没有检查,但我怀疑上面描述的user274204方法可能是符合CLR的方法 公开课表格1
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
End Class看起来很多代码只是一堆解释发生了什么的注释。请注意,对于多维数组,这只适用于最后一个维度。这里有一个链接,提供更多信息: