1

私はインターネット上で以下のようなコードを見つけました(わずかに変更されています)。

Webページのコンテンツを要求するだけです。

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

ただし、2つの警告が表示されます。

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

デフォルトでは何も設定しないでください。こうすることで、コンパイラに何をしているのかがわかります:)

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

警告は、GetResponseStreamでエラーが発生した場合、srReadがnullになり、Null例外が発生するためです。

これを処理する1つの方法は、これらのオブジェクトを自動的に破棄する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がオブジェクトをUsingキーワードの代わりにNothingに設定することを提案する方法を実行することもできます。そうすれば、これが最終的に必要になります。

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 に答える