2010-12-22 56 views
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塊。

這樣做還是我可以使用不同的方法防止警告?

在此先感謝您的啓發! :)

回答

3

警告是因爲如果GetResponseStream上有錯誤,那麼您的srRead將爲空,導致Null異常。處理這種

的一種方法是使用使用,它會自動處理這些對象的

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 

你也可以走的路邪惡博士建議設置對象爲Nothing,而不是使用關鍵字,那麼你就希望這在默認情況下,終於

Finally 
     If Str Is Not Nothing Then 
      Str.Close 
     End If 
     If srRead Is Not Nothing Then 
      srRead.Close 
     End If 
End Try 
+0

使用`Using`時,我不必關閉連接嗎? – PeeHaa 2010-12-22 21:46:59

+0

不使用使用語句爲你做。 (關閉與Dispose相同) – 2010-12-22 21:50:41

10

您可以簡單地設置他們什麼,這樣你就告訴編譯器你知道你在做什麼:)

Dim Str As System.IO.Stream = Nothing