2013-03-31 12 views
0

所以,我有以下的VB代碼: 「txtVern」如何在VB中的代碼中的其他位置調用變量?

Try 
     Using verSR As New StreamReader(appDataVersionLoc) 
      Dim txtVern As String 
      txtVern = verSR.ReadToEnd() 
     End Using 
    Catch ex As Exception 
     Dim verFile As System.IO.FileStream 
     verFile = System.IO.File.Create(appDataVersionLoc) 
     My.Computer.FileSystem.WriteAllText("appDataVersionLoc", "0.0.0.0", True) 
     MessageBox.Show("Version file missing/corrupt, created a new one.") 
    End Try 

見該變量稱爲我試圖在try-end try塊外的代碼中的其他地方使用它。 差不多這樣的:

Try 
     Using verSR As New StreamReader(appDataVersionLoc) 
      Dim txtVern As String 
      txtVern = verSR.ReadToEnd() 
     End Using 
    Catch ex As Exception 
     Dim verFile As System.IO.FileStream 
     verFile = System.IO.File.Create(appDataVersionLoc) 
     My.Computer.FileSystem.WriteAllText("appDataVersionLoc", "0.0.0.0", True) 
     MessageBox.Show("Version file missing/corrupt, created a new one.") 
    End Try 

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah 

    Dim currentversion As String = txtVern 

現在,我是一個完整的VB小白,而我得到這個錯誤:

'txtVern' is not declared. It may be inaccessible due to its protection level.

我該如何解決這個問題? 謝謝!

回答

2

在任何塊內聲明的變量僅在該塊內可見。您以前Try塊移動聲明:

Dim txtVern As String = String.Empty 
Try 
    Using verSR As New StreamReader(appDataVersionLoc) 
     txtVern = verSR.ReadToEnd() 
    End Using 
Catch ex As Exception 
    Dim verFile As System.IO.FileStream 
    verFile = System.IO.File.Create(appDataVersionLoc) 
    My.Computer.FileSystem.WriteAllText("appDataVersionLoc", "0.0.0.0", True) 
    MessageBox.Show("Version file missing/corrupt, created a new one.") 
End Try 

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah 

Dim currentversion As String = txtVern 
+0

謝謝!這工作! – Dubstaphone

0

在聲明你的變量txtVern在try塊就會限制其範圍try塊。嘗試在子例程的開頭聲明它們。

相關問題