宣告變數

在 VB.NET 中,每個變數必須在使用之前宣告(如果 Option Explicit 設定為 On )。有兩種宣告變數的方法:

  • FunctionSub 裡面:
Dim w 'Declares a variable named w of type Object (invalid if Option Strict is On)
Dim x As String 'Declares a variable named x of type String
Dim y As Long = 45 'Declares a variable named y of type Long and assigns it the value 45
Dim z = 45 'Declares a variable named z whose type is inferred
           'from the type of the assigned value (Integer here) (if Option Infer is On)
           'otherwise the type is Object (invalid if Option Strict is On)
           'and assigns that value (45) to it 

有關 Option ExplicitStrictInfer 的完整詳細資訊,請參閱此答案

  • ClassModule 裡面:

這些變數(在此上下文中也稱為欄位)將可以被宣告的 Class 的每個例項訪問。它們可以從宣告的 Class 外部訪問,具體取決於修飾符(PublicPrivateProtectedProtected FriendFriend

Private x 'Declares a private field named x of type Object (invalid if Option Strict is On)
Public y As String 'Declares a public field named y of type String
Friend z As Integer = 45 'Declares a friend field named z of type Integer and assigns it the value 45

這些欄位也可以使用 Dim 宣告,但含義會根據封閉型別而變化:

Class SomeClass
    Dim z As Integer = 45 ' Same meaning as Private z As Integer = 45
End Class

Structure SomeStructure
    Dim y As String ' Same meaning as Public y As String
End Structure