奇怪的错误(索引绑定数组vb.net)

时间:2015-07-03 05:36:40

标签: arrays vb.net list integer

我正在尝试创建一个包含5个元素的列表

   Dim clickcount As Integer = 0
   Dim clickindex(6) As Integer
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button5.Click, Button4.Click, Button6.Click
    Dim btn As Button
    btn = CType(sender, Button)

    If btn.BackColor = Color.Red Then
        btn.BackColor = Color.Green
        Dim strList As List(Of Integer) = clickindex.ToList()
        strList.Remove(btn.Tag)
        clickindex = strList.ToArray()
        clickcount -= 1
    ElseIf btn.BackColor = Color.Green Then
        If clickcount = 5 Then
            MsgBox("Max Reach")
            Exit Sub
        End If
        btn.BackColor = Color.Red
        clickcount += 1
        clickindex(clickcount) = btn.Tag

    End If

End Sub

每次点击一个按钮,它都会将按钮编号添加到列表中,最大点击按钮为5 再次单击该按钮时,它将从阵列中删除按钮编号。

我的问题是,当我点击几次时,会发生错误,它表示索引绑定了数组,但索引仍然在范围内。 有谁知道问题在哪里?

1 个答案:

答案 0 :(得分:0)

问题的根源:

你的问题在于:

    Dim strList As List(Of Integer) = clickindex.ToList()
    strList.Remove(btn.Tag)
    clickindex = strList.ToArray()

看一下以下示例: 让我们说clickindex看起来如下

 clickindex = {1,0,3,0,0,0,0} 'Dim clickindex(6) As Integer declares an array with length '7'

Dim strList As List(Of Integer) = clickindex.ToList()之后,strList现在是List of Integer,包含7个项目:{1,0,3,0,0,0,0}

   strList.Remove(btn.Tag)
   'strList is nog a List of Integer with 6 Items (btn.Tag has been removed)
   clickIndex = lst.ToArray()
   'ClickIndex is now an Array with 6 items instead of the original 7

可能的解决方案

为什么不使用以下(更简单的)代码:

Dim clickindex As new List(Of Integer)
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button5.Click, Button4.Click, Button6.Click
    Dim btn As Button
    btn = CType(sender, Button)

    If btn.BackColor = Color.Red Then
        btn.BackColor = Color.Green
        strList.Remove(btn.Tag)
    ElseIf btn.BackColor = Color.Green Then
        If strList.Count >= 5 Then
            MsgBox("Max Reach")
            Exit Sub
        End If
        btn.BackColor = Color.Red
        strList.Add(btn.Tag)

    End If

End Sub