2010-11-27 67 views
3

我是VB的n00b和想知道如何使一個變量可用跨多個子。這只是一個測試應用程序,以熟悉VB。 我的代碼:VB 2010'變量'未被聲明。它可能是無法訪問,由於它的保護水平

Public Class Sentences 

Private Sub SentenceBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SentenceBox.TextChanged 
    If Me.Text = Trim(Sentence) Then 
     MsgBox("Good job!") 
     Main_Menu.Show() 
     Me.Close() 
    End If 
End Sub 

Private Sub ABCs_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    Dim random As Integer = CInt((Rnd() * 10) + 1) 
    Dim Sentence As String 


    Select Case random 
     Case 1 
      Sentence = "The quick brown fox jumped over the lazy dog!" 
     Case 2 
      Sentence = "Hi there, how are you doing?" 
     Case 3 
      Sentence = "What is the answer to life?" 
     Case 4 
      Sentence = "The cat in the hat was fat." 
     Case 5 
      Sentence = "John and Sam had always been fat." 
     Case 6 
      Sentence = "The snow is falling hard." 
     Case 7 
      Sentence = "Here, dinner is always served nightly." 
     Case 8 
      Sentence = "The dog barks at the passing cars." 
     Case 9 
      Sentence = "The dust settles on the books." 
     Case 10 
      Sentence = "Fire burns brightly when you add kerosene." 
    End Select 
End Sub 

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 
    SentenceBox.Text = Sentence 

    End Sub 
End Class 

我的錯誤是:

「刑期」 未聲明。這可能是在accessable,由於它的保護級別「

+0

我不認爲你發佈的代碼實際上產生了這個錯誤信息。 – 2010-11-28 17:33:54

回答

6

的變量VB.NET有一個非常特殊的scope,根據他們聲明的方式和位置限制它們在代碼的各個部分的可用性。

Sentence您的Sentence變量具有過程級別的範圍,這意味着它僅在聲明它的過程中可用。就你的情況而言,它在ABCs_Load方法(「Sub」)中聲明,所以它只能用於該方法內的代碼。

相反,如果你希望能夠訪問Sentence變量方法中的任何你們班(Forms總是班VB.NET),你可以聲明與模塊級範圍的變量。爲此,您需要將private field添加到Sentences類,以外的任何特定方法(子或函數)的。該聲明將是這個樣子:

Private Sentence As String 


當然,你也可以變量聲明爲Public代替Private,這將使其成爲當前類以外的可用於其他類。例如,如果您希望能夠訪問Sentence變量的內容的第二個表單可以在第一個表單的類中聲明爲Public,然後從秒中的某個方法訪問它窗體類,像這樣:

MessageBox.Show(myForm1.Sentence) 

注意,因爲它的另一種形式中說謊(比它被訪問在一個不同的類),你必須參考完全限定它。這就像你的家人可能會給你打電話「邁克」,但其他人必須打電話給你「邁克瓊斯」,以區分你與「邁克史密斯」。「


如要進一步瞭解,也請參閱MSDN上以下相關文章:下將這個

-1

」:

Dim Sentence As String = String.Empty 
公共類句子「

並從ABCs_Load範圍中刪除聲明。

0

將行Dim Sentence As String從ABCs_Load移動到Public Class Sentences之後。

這將使變量Sentence可用於班級句子中的所有子類和函數。

0

如果您收到此爲網頁上的每個三夏然後用鼠標右鍵單擊該項目或錯誤的文件夾和「轉換爲WebApplication的」自動生成其designer.vb文件(在那裏他們的部分得到聲明類同名)。

0

,你應該把它聲明爲公用變量public sentence as string=string.empty ,但如果是你,我剛剛宣佈它在全班同學 樣品

public class NameOfClass 
 
    dim sentence as string=string.empty 
 

 
    public sub nameOfSub 
 
    --you can use the variable 'sentence' here 
 
    end sub 
 
    public sub nameOfSub2 
 
    --you can use the variable 'sentence' here 
 
    end sub 
 
end class

相關問題