I have this code:
Module Module1
Dim x As Integer = 1
Dim y As Integer = 1
Dim arr(x, y) As开发者_Python百科 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
And with it I'm trying to change the upper bound of array dimensions. But I get this error:"Index was outside the bounds of the array". What I'm doing wrong?
You can't change the upper-bound of an array like that in .NET. If you need a dynamically sized Array I'd suggest looking at List
as it allows you to do all of this.
You'll want to do something like:
Dim yourStrings AS List(Of List(Of String)) = New List(Of New List(Of String)
To convert this to a 2-D Array:
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
From 2-D to List(Of 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
If you declare array with dimension x and y, to use outbound value you have to redim array using redim() command:
MSDN Redim Command Doc
Example:
Dim intArray(10, 10, 10) As Integer
ReDim Preserve intArray(10, 10, 20)
You can use ReDim
to reallocate memory as needed.
I made this by myself:
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
It works with 2D arrays, but can be modified to work with unlimited number of arrays by adding a ParamArray of dimensions.
I don't know when this syntax was introduced, but you can define an array with a dynamic size using:
Dim arr As String(,) = New String(x,y){}
or simply
Dim arr = New String(x,y){}
or using the original example
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
(not tested).
I think this syntax is preferable to the old (VB6 style) ReDim statement.
精彩评论