动态多维数组的问题多维、数组、动态、问题

2023-09-06 21:49:12 作者:给烟不给火纯属调戏我

我有这个code:

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

和它我试图改变上限阵列尺寸。但我得到这个错误:索引数组的范围之外。我做错了什么?

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?

推荐答案

您不能更改上限一样,在.NET数组。如果你需要一个动态大小的数组我建议在看列表,因为它可以让你做这一切。

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

从2-D到表(表中(字符串))

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
 
精彩推荐
图片推荐