2014-02-23 29 views
1

在下面的代碼中,我希望能夠訪問任何子例程中的變量enteredusernameenteredpassword。我怎麼做到這一點?如何讓我的程序中的所有子程序訪問某個變量?

Using rdr As New FileIO.TextFieldParser("f:\Computing\Spelling Bee\stdnt&staffdtls.csv") 
     rdr.TextFieldType = FieldType.Delimited 
     rdr.Delimiters = New String() {","c} 
     item = rdr.ReadFields() 
    End Using 
    Console.Write("Username: ") 
    enteredusername = Console.ReadLine 
    Console.Write("Password: ") 
    Dim info As ConsoleKeyInfo 
    Do 
     info = Console.ReadKey(True) 
     If info.Key = ConsoleKey.Enter Then 
      Exit Do 
     End If 
     If info.Key = ConsoleKey.Backspace AndAlso enteredpassword.Length > 0 Then 
      enteredpassword = enteredpassword.Substring(0, enteredpassword.Length - 1) 
      Console.Write(vbBack & " ") 
      Console.CursorLeft -= 1 
     Else 
      enteredpassword &= info.KeyChar 
      Console.Write("*"c) 
     End If 
    Loop 
    Dim foundItem() As String = Nothing 
    For Each line As String In File.ReadAllLines("f:\Computing\Spelling Bee\stdnt&staffdtls.csv") 
     Dim item() As String = line.Split(","c) 
     If (enteredusername = item(0)) And (enteredpassword = item(1)) Then 
      foundItem = item 
      Exit For 
     End If 
    Next 
+0

使它們成爲類級變量。 – Tim

回答

1

要允許程序中的所有類訪問變量,您需要將其設置爲類級別並使用PublicShared來定義它。

演示:

Public Class MainClass 

    Public Shared enteredusername As String 
    Public Shared enteredpassword As String 

    Private Sub SomeSub() 
     ' Some Code ... 

     ' You can access it here: 
     enteredusername = "something" 
     enteredpassword = "something else" 

     ' ... More Code ... 
    End Sub 
End Class 

Public Class AnotherClass 
    'Also, please note, that this class can also be in another file. 

    Private Sub AnotherSub() 
     ' Some Code ... 

     ' You can also access the variable here, but you need to specify what class it is from, like so: 
     Console.WriteLine(MainClass.enteredusername) 
     Console.WriteLine(MainClass.enteredpassword) 

     ' ... More Code ... 
    End Sub 
End Class 

 

此外,在一個單獨的說明中,PublicShared改性劑也可以在方法中使用。如果您制定方法Private或者不指定任何內容,則只能從同一個類中的方法訪問該方法。如果你只使用Public,其他類可以訪問方法,但他們將需要創建類的實例,像這樣:

Dim AC As New AnotherClass 
AC.AnotherSub() 

如果使用PublicShared修飾兩種,其他的班會能夠直接訪問該方法,而無需創建新實例。但是,您必須注意,Shared方法不能訪問非Shared方法或變量。其他類可以訪問Public Shared方法,如下所示:

AnotherClass.AnotherSub() 
0

這取決於範圍。如果你希望所有在當前類的子程序,以便能夠訪問他們,然後讓它們的類

Class TheClassName 
    Dim enteredusername As String 
    Dim enteredpassword As String 
    ... 
End Class 

的領域。如果你想在所有的類和模塊的所有子程序能夠訪問他們,然後讓他們一個模塊級別字段

Module TheModuleName 
    Dim enteredusername As String 
    Dim enteredpassword As String 
    ... 
End Module 

雖然我建議不要這種方法。當然,這在短期內更容易,因爲它需要較少的儀式和對價值觀的使用的想法。但長期來說,它會降低代碼庫的可維護性

+0

這不完全正確。您還可以使用「公共」和「共享」修飾符來允許所有類訪問。 –

相關問題