1

我在互联网上找到了一些代码如下(稍作修改)。

它只是请求网页的内容。

Private Sub readWebpage(ByVal url As String)
    Dim Str As System.IO.Stream
    Dim srRead As System.IO.StreamReader
    Try
        ' make a Web request
        Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
        Dim resp As System.Net.WebResponse = req.GetResponse
        Str = resp.GetResponseStream
        srRead = New System.IO.StreamReader(Str)
        ' read all the text 
        textContent.text = srRead.ReadToEnd
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Unable to download content from: " & url)
    Finally
        srRead.Close()
        Str.Close()
    End Try
End Sub

但是我收到两个警告:

Warning 1   Variable 'srRead' is used before it has been assigned a value. A null reference exception could result at runtime.


Warning 2   Variable 'Str' is used before it has been assigned a value. A null reference exception could result at runtime.

我知道我可以简单地忘记Finally并将代码添加到 try 块。

这是要走的路还是我可以使用不同的方法来防止警告?

提前感谢您启发我!:)

4

2 回答 2

10

您可以简单地将它们默认设置为 Nothing,这样您将通知编译器您知道自己在做什么:)

Dim Str As System.IO.Stream = Nothing
于 2010-12-22T21:44:24.407 回答
3

警告是因为如果 GetResponseStream 出现错误,那么您的 srRead 将为空,从而导致空异常。

处理此问题的一种方法是使用 Using,它将自动处理这些对象

 Private Sub readWebpage(ByVal url As String)
        Try
            ' make a Web request
            Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
            Dim resp As System.Net.WebResponse = req.GetResponse
            Using Str As System.IO.Stream = resp.GetResponseStream
                Using srRead As System.IO.StreamReader = New System.IO.StreamReader(Str)
                    textContent = srRead.ReadToEnd
                End Using
            End Using


    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Unable to download content from: " & url)

    End Try
  End Sub

你也可以按照 Dr. Evil 建议的方式将对象设置为 Nothing 而不是 Using 关键字,然后你会想要在你的 finally

Finally 
        If Str Is Not Nothing Then
            Str.Close
        End If
        If srRead Is Not Nothing Then
            srRead.Close
        End If
End Try
于 2010-12-22T21:42:50.670 回答