vb.net - 如何在 foreach 循环中不处理任何内容

标签 vb.net foreach

我有以下功能:

 Public Sub performautowebrowserOperations()
    Try
        For Each link As HtmlElement In WebBrowser2.Document.GetElementsByTagName("input") 'sometimes throws a null reference exception
            If link.GetAttribute("value") IsNot Nothing Then
                If link.GetAttribute("value") = "Compare prices" Then
                    link.InvokeMember("click")
                End If
            End If
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

有时注释行会抛出 NullReferenceException。为什么会这样,如何解决?

最佳答案

我会更改 GetElementsByTagName ,使其位于 For Each 语句之外,这样可以更轻松地检查 Collection 是否为 Null 或 Empty。

Public Sub performautowebrowserOperations()
    Try
        Dim elements As HtmlElementCollection = WebBrowser2.Document.GetElementsByTagName("input")
        If Not IsNothing(elements) And elements.Count > 0 Then
            For Each link As HtmlElement In elements
                If link.GetAttribute("value") IsNot Nothing Then
                    If link.GetAttribute("value") = "Compare prices" Then
                        link.InvokeMember("click")
                    End If
                End If
            Next
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

关于vb.net - 如何在 foreach 循环中不处理任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273327/

相关文章:

vb.net - 如何在一行中分割和修剪字符串

Java For 循环差异

angular - _.forEach 循环值改变所有继承的数据

Powershell foreach 暂停后执行

vb.net - "If a < b < c Then"在 vb.net 中实际上做了什么?

mysql - VB.NET 中的 SQL 查询不断出现带有通配符的错误

.net - WPF 拖放 - DragLeave 何时触发?

vb.net - 罗斯林错误?在非共享成员上,我收到错误,我正在使用 'shared member initializer'

php - 如何使用 foreach 循环动态执行 mysql 查询?

R - foreach 循环,verbose=TRUE