VB - 索引超出范围?

时间:2014-02-09 09:02:19

标签: vb.net indexoutofboundsexception

哦,我的上帝,我讨厌这件事,我尝试了数百万种方法,却找不到合适的方法。让我解释一下:

我正在测试每一行并检查第一个单词是否“复制”好吗?在单词copy之后,我想看看下一个单词是否为“1”,第三个是“<”最后是“>” ,如果满足所有这些条件,则“<”之间的文本和“>”需要存储在变量“copy1”中(即使它们之间有多于1个字)。

我的代码是什么:

For i = 0 To lstCode.Items.Count - 1

Dim str As String = lstCode.Items.Item(i)

Dim strA() As String = Split(str)

Dim copy1 as string

Dim copy2 as string

Select Case strA(0)


Case copy


If strA(1) = "1" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then

copy1 = ""

For lr As Integer = 3 To strA.Count - 2

copy1 &= (strA(lr) & " ")

Next

End if

End select

而且,当我调试它时,我得到错误:索引超出了数组的范围......有没有人有任何想法?


有一些重要我忘记添加,这是整个代码:

 Case "copy"

                    If strA(1) = "1" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then
                        copy1 = ""

                        For lr As Integer = 3 To strA.Count - 2
                            copy1 &= (strA(lr) & " ")
                        Next


                    ElseIf strA(1) = "2" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then
                        copy2 = ""

                        For lrs As Integer = 3 To strA.Count - 2
                            copy2 &= (strA(lrs) & " ")
                        Next



                    ElseIf strA(1) = "run" Then
                        Try
                            IO.File.Copy(copy1, copy2)
                        Catch ex As IO.IOException
                        End Try
                    End If


            End Select

所以一切都像魅力一样:复制1&lt; c:\ csb.log&gt; ,副本2&lt; c:\ blabla.txt&gt;但是当“复制运行”语句出现时,它会给我错误...

1 个答案:

答案 0 :(得分:1)

您需要更改运算符And with AndAlso

第二个将Short Circuit Evaluation应用于您的表达式,这意味着如果第一个表达式为false,则不会评估同一行上的第二个,第三个表达式等等。

在你的行

 If strA(1) = "1" And strA(2)  = "<" And .......

当值为“Run”时,您仍然会评估表达式strA(2) = "<",但索引2处没有元素,因此您会收到错误。