我在互聯網上發現了一些代碼(稍作修改)。防止未分配值的變量的警告嘗試
它只是請求網頁的內容。
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塊。
這樣做還是我可以使用不同的方法防止警告?
在此先感謝您的啓發! :)
使用`Using`時,我不必關閉連接嗎? – PeeHaa 2010-12-22 21:46:59
不使用使用語句爲你做。 (關閉與Dispose相同) – 2010-12-22 21:50:41