ReDim不会减少阵列

时间:2015-07-08 18:14:52

标签: arrays vb.net

如果这是重复的,抱歉,我先做了搜索。

Visual Basic 2013,该分配特定于数组,因此我无法使用列表。将项添加到数组并删除它们,ReDim将放大但不减少它。代码:

    Private Strings(-1) As String

   Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
    ReDim Preserve Strings(Strings.Length)
    Strings(Strings.Length - 1) = TextBox.Text
    ShowStrings()
    TextBox.Text = ""
    Label.Text = Strings.Length
End Sub

Private Sub RemoveButton_Click(sender As Object, e As EventArgs) Handles RemoveButton.Click
    Dim length As Integer = Strings.Length - 1
    Dim what As Integer = ListBox.SelectedIndex

    Do While what < length
        Strings(what) = Strings(what + 1)
        what = what + 1
    Loop
    ReDim Preserve Strings(length)
    Label.Text = Strings.Length
    ShowStrings()
End Sub

正如我所说,AddButton中的ReDim成功地扩大了数组,而RemoveButton的ReDim不会缩小数组。我试过没有保留,同样的问题,所以不是。

感谢您的任何想法。再次,我意识到这不是最佳解决方案(哎呀,如果这不是关于数组的作业,我只是使用ListBox的方法),所以让我们来看看。请保持参数。

1 个答案:

答案 0 :(得分:1)

更改

ReDim Preserve Strings(length)

ReDim Preserve Strings(length - 1)