2014-02-23 3 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 

의 필드를 만들 수있을합니다 그들에게 모듈 레벨 필드

나는이 방법을 권장한다. 짧은 시간에 더 쉽게 의식을하고 값의 사용에 대해 생각하기 때문에 쉽습니다. 그러나 장기적으로 코드베이스의 유지 보수성을 감소시키는 역할을합니다.

+0

이것은 완전히 정확하지 않습니다. 'Public'과'Shared' 수정자를 사용하여 모든 클래스로부터 접근을 허용 할 수 있습니다. –