获取不应该发生的 String.Chars() 数组"System.IndexOutOfRangeException"



有谁能破解我是如何得到这个"System.IndexOutOfRangeException"的?我已经查看了代码,字符串甚至不可能是空的,因为我创建的方法如果捕捉到异常,就会返回一个包含单词"Nothing"的字符串。

以下是我得到的例外:

Do While (Not (nodeStep Is Nothing))
    stepCmd = cmd + (XPathCommand.STEPCMD + ("/tr[" + stepCount.ToString + "]"))
    stepString = htmlManager.GetTextbyNode(htmlManager.GetNodebyXPath(stepCmd))
    stepChar = stepString.Chars(0) '<--- Exception thrown here!
    Select Case stepChar
        Case "D"
            testScript.StepDesc.Add(stepString.Replace("Description: ", ""))
        Case "E"
            testScript.StepExpect.Add(stepString.Replace("Expected: ", ""))
        Case "S"
            If Not (testScript.StepDesc.Count = testScript.StepExpect.Count) Then
                testScript.StepExpect.Add("< No expected step here >")
            End If
    End Select
    stepCount += 1
    nodeStep = htmlManager.GetNodebyXPath(cmd + (XPathCommand.STEPCMD + ("/tr[" + stepCount.ToString + "]")))
Loop

现在,htmlManager.GetTextbyNode方法本身就是它获取HtmlAgilityPack.HtmlNode并在首先清理text String之后返回节点中的所有文本的地方。问题是,该方法有一个catch-all(对于其中没有任何文本的节点)来返回String"Nothing",如下所示:

Function GetTextbyNode(ByVal node As HtmlAgilityPack.HtmlNode) As String
    Try
        Return StringCleaner.Clean(node.InnerText)
    Catch
        'If find a NULL Text node
    End Try
    Return "Nothing"
End Function

所以,即使传递的节点是否有NULL文本,我也应该返回一个有效的String,对吧?如果我得到一个有效的字符串,那么string.Chars(0)应该至少有一个字母?我不应该返回NULL字符串,对吗?还是我错过了什么?

正如注释所说,很可能是那个节点。InnerText为空,因此我建议更改此方法

Function GetTextbyNode(ByVal node As HtmlAgilityPack.HtmlNode) As String
    Try
        If not String.isNullOrEmpty(node.InnerText) then
           Return StringCleaner.Clean(node.InnerText)
        End If
    Catch
        'If find a NULL Text node
    End Try
    Return "Nothing"
End Function

最新更新