我有这段代码:
Module Module1
Dim x As Integer = 1
Dim y As Integer = 1
Dim arr(x, y) As String
Sub Main()
x += 2
y += 3
For ix = 0 To x
For iy = 0 To y
arr(ix, iy) = String.Format("{0}:{1}", ix, iy)
Next
Next
For ix = 0 To x
For iy = 0 To y
Console.WriteLine(arr(ix, iy))
Next
Next
Console.Read()
End Sub
End Module
有了它,我试图改变数组维度的上限。但是我得到了这个错误:“索引超出了数组的范围”。我做错了什么?
答案 0 :(得分:3)
您无法像.NET中那样更改数组的上限。如果您需要一个动态大小的数组,我建议您查看List
因为它允许您完成所有这些。
你会想做类似的事情:
Dim yourStrings AS List(Of List(Of String)) = New List(Of New List(Of String)
将其转换为二维数组:
Dim maxListLength As Integer = 0
For Each subList In yourStrings
maxListLength = If(subList.Length > maxListLength, subList.Length, maxListLength)
Next
Dim yourArray(yourString.Length - 1, maxListLength -1) As String
Dim x As Integer = 0
Dim y As Integer = 0
For Each subList In yourString
For Each str In subList
yourArray(x, y) = str
y = y + 1
Next
x = x + 1
Next
从2-D到List(List(Of String))
Dim yourList As List(Of List(Of String)) = New List(Of List(Of String))
For i = 0 To ArrayXSize
Dim thisXString = New List(Of String)
For j = 0 To ArrayYSize
thisXStrings.Add(yourArray(i,j))
Next
yourList.Add(thisXStrings)
Next
答案 1 :(得分:0)
您可以根据需要使用ReDim
重新分配内存。
答案 2 :(得分:0)
如果使用维x和y声明数组,要使用出站值,必须使用redim()命令重新排列数组:
示例强>:
Dim intArray(10, 10, 10) As Integer
ReDim Preserve intArray(10, 10, 20)
答案 3 :(得分:0)
我自己做了这个:
Private Function MultiReDim(ByVal a As Array, ByVal dimOne As Short, ByVal dimTwo As Short) As String(,)
Dim newArr(dimOne, dimTwo) As String
For x = 0 To newArr.GetUpperBound(0)
For y = 0 To newArr.GetUpperBound(1)
If x <= a.GetUpperBound(0) AndAlso y <= a.GetUpperBound(1) Then
newArr(x, y) = a(x, y)
Else
newArr(x, y) = Nothing
End If
Next
Next
Return newArr
End Function
它适用于2D数组,但可以通过添加尺寸的ParamArray进行修改以使用无限数量的数组。
答案 4 :(得分:0)
我不知道何时引入了这种语法,但您可以使用以下命令定义具有动态大小的数组:
Dim arr As String(,) = New String(x,y){}
或只是
Dim arr = New String(x,y){}
或使用原始示例
Module Module1
Dim x As Integer = 1
Dim y As Integer = 1
Dim arr(x, y) As String
Sub Main()
x += 2
y += 3
arr = New String(x,y){}
For ix As Integer = 0 To x
For iy As Integer = 0 To y
arr(ix, iy) = String.Format("{0}:{1}", ix, iy)
Next
Next
For ix As Integer = 0 To x
For iy As Integer = 0 To y
Console.WriteLine(arr(ix, iy))
Next
Next
Console.Read()
End Sub
End Module
(未经测试)。
我认为这种语法比旧的(VB6风格)ReDim语句更好。