2010-12-22 4 views
1

인터넷에서 다음과 같이 일부 코드가 발견되었습니다 (약간 수정 됨).시도에서 값이 할당되지 않은 변수에 대한 경고를 방지합니다.

단순히 웹 페이지의 콘텐츠를 요청합니다. 나는 단순히 Finally 잊고 try 블록에 코드를 추가 할 수 있습니다 알고

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. 

:

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 

그러나 나는이 경고를 얻을.

다른 방법을 사용하여 경고 메시지를 표시 할 수 있습니까?

미리 감사드립니다. :)

답변

3

GetResponseStream에 오류가 있으면 srRead가 Null 예외가 발생하여 null이 될 수 있기 때문에 경고 메시지가 표시됩니다. 이 처리하는

한 가지 방법은 또한 이블 박사 후 대신 사용 키워드 Nothing으로 객체를 사용하면됩니다 설정 제안 길을 갈 수

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 

자동으로 이러한 개체를 처리 할 사용하여 사용하는 것입니다 당신은 당신이 무엇을하고 있는지 알고, 기본적으로 마지막

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

+0

아니요 using 문을 사용하면 도움이됩니다. (닫기는 Dispose와 동일합니다.) –

+0

좋습니다. 나는 이것이 최선의 접근이라고 생각한다. 모든 정보 주셔서 감사합니다! – PeeHaa

10

당신은 단순히 그들에게 설정할 수 있습니다 아무것도 당신이 컴파일러에 알려거야 이런 식으로이 원하는 :)

Dim Str As System.IO.Stream = Nothing 
+0

감사합니다! – PeeHaa

+0

이 방법은 내가 사용하지만 vb.net에서 다음과 같이 할 수 없다는 것을 싫어한다. Dim a, b, c, d는 double = 아무것도 아니야'다음과 같이해야한다. Dim a as Double = Nothing'' Dim b as Double = Nothing ...'경고를 종료하기 위해 더 많은 코드 행이 있습니다. –

+0

이것은 우습게 보입니다. VB.NET이 싫어. 당신은'Dim Str As System.IO.Stream'이 동등하다고 생각할 것입니다. – crush

관련 문제