使用基本类型声明和分配变量

Visual Basic 中的变量使用 Dim 关键字声明。例如,这声明了一个名为 counter 的新变量,其数据类型为 Integer

Dim counter As Integer

变量声明还可以包括访问修饰符 ,例如 PublicProtectedFriendPrivate。这与变量的范围一起使用以确定其可访问性。

访问修饰符 含义
上市 所有可以访问封闭类型的类型
受保护 只有封闭类和从它继承的类
朋友 可以访问封闭类型的同一程序集中的所有类型
受保护的朋友 封闭类及其继承者,可以访问封闭类的同一程序集中的类型
私人的 只有封闭式
静态的 仅在局部变量上,仅初始化一次。

作为简写,Dim 关键字可以用变量声明中的访问修饰符替换:

Public TotalItems As Integer
Private counter As Integer

支持的数据类型如下表所示:

类型 别号 内存分配
为 SByte N / A 1 个字节 Dim example As SByte = 10
INT16 2 个字节 Dim example As Short = 10
INT32 整数 4 字节 Dim example As Integer = 10
Int64 8 个字节 Dim example As Long = 10
N / A 4 字节 Dim example As Single = 10.95
double N / A 8 个字节 Dim example As Double = 10.95
十进制 N / A 16 个字节 Dim example As Decimal = 10.95
布尔 N / A 通过实施平台来说明 Dim example As Boolean = True
Char N / A 2 个字节 Dim example As Char = "A"C
字符串 N / A 式 资源 Dim example As String = "Stack Overflow"
日期时间 日期 8 个字节 Dim example As Date = Date.Now
字节 N / A 1 个字节 Dim example As Byte = 10
UINT16 USHORT 2 个字节 Dim example As UShort = 10
UInt32 UInteger 4 字节 Dim example As UInteger = 10
答:64 ULONG 8 个字节 Dim example As ULong = 10
宾语 N / A 4 字节 32 位架构,8 字节 64 位架构 Dim example As Object = Nothing

还存在可用于替换文本类型和/或强制文字类型的数据标识符和文字类型字符:

类型(或别名) 标识符类型字符 字面型字符
N / A example = 10S
整数 Dim example% example = 10%example = 10I
Dim example& example = 10&example = 10L
Dim example! example = 10!example = 10F
double Dim example# example = 10#example = 10R
十进制 Dim example@ example = 10@example = 10D
Char N / A example = "A"C
字符串 Dim example$ N / A
USHORT N / A example = 10US
UInteger N / A example = 10UI
ULONG N / A example = 10UL

积分后缀也可用于十六进制(&H)或八进制(&O)前缀:
example = &H8000Sexample = &O77&

日期(时间)对象也可以使用文字语法定义:
Dim example As Date = #7/26/2016 12:8 PM#

一旦声明了变量,它将存在于包含类型的范围内,例如 SubFunction,例如:

Public Function IncrementCounter() As Integer
    Dim counter As Integer = 0
    counter += 1

    Return counter
End Function

计数器变量只会在 End Function 之前存在,然后才会超出范围。如果在函数外部需要此计数器变量,则必须在类/结构或模块级别定义它。

Public Class ExampleClass

    Private _counter As Integer
   
    Public Function IncrementCounter() As Integer
       _counter += 1
       Return _counter
    End Function

End Class

或者,你可以使用 Static(不要与 Shared 混淆)修饰符来允许局部变量在其封闭方法的调用之间保留它的值:

Function IncrementCounter() As Integer
    Static counter As Integer = 0
    counter += 1

    Return counter
End Function