声明变量

在 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