Visual Basic中的变量使用Dim关键字来声明。例如,这声明了一个名为counter的数据类型为Integer的新变量:
Dim counter As Integer
变量声明还可以包括访问修饰符,例如Public、Protected、Friend或Private。这与变量的作用域一起确定其可访问性。
访问修饰符 | 意义 |
---|---|
Public | 可以访问封闭类型的所有类型 |
Protected | 只有封闭类和从中继承的类 |
Friend | 同一程序集中可以访问封闭类型的所有类型 |
Protected Friend | 封闭类及其继承者,或同一程序集中可以访问封闭类的类型 |
Private | 只有封闭类型 |
Static | 只在局部变量上,并且只初始化一次。 |
简而言之,Dim关键字可以替换为变量声明中的访问修饰符:
Public TotalItems As Integer Private counter As Integer
下表列出了支持的数据类型:
Type | Alias | 内存分配 | 例子 |
---|---|---|---|
SByte | N/A | 1 byte | Dim example As SByte = 10 |
Int16 | Short | 2 bytes | Dim example As Short = 10 |
Int32 | Integer | 4 bytes | Dim example As Integer = 10 |
Int64 | Long | 8 bytes | Dim example As Long = 10 |
Single | N/A | 4 bytes | Dim example As Single = 10.95 |
Double | N/A | 8 bytes | Dim example As Double = 10.95 |
Decimal | N/A | 16 bytes | Dim example As Decimal = 10.95 |
Boolean | N/A | 由实现平台决定 | Dim example As Boolean = True |
Char | N/A | 2 Bytes | Dim example As Char = "A"C |
String | N/A | source | Dim example As String = "Stack Overflow" |
DateTime | Date | 8 Bytes | Dim example As Date = Date.Now |
Byte | N/A | 1 byte | Dim example As Byte = 10 |
UInt16 | UShort | 2 bytes | Dim example As UShort = 10 |
UInt32 | UInteger | 4 bytes | Dim example As UInteger = 10 |
UInt64 | ULong | 8 bytes | Dim example As ULong = 10 |
Object | N/A | 4字节32位体系结构,8字节64位体系结构 | Dim example As Object = Nothing |
还存在可用于替换文本类型和或强制文本类型的数据标识符和文本类型字符:
Type (or Alias) | 标识符类型字符 | 文字类型字符 |
---|---|---|
Short | N/A | example = 10S |
Integer | Dim example% | example = 10% or example = 10I |
Long | Dim example& | example = 10& or example = 10L |
Single | Dim example! | example = 10! or example = 10F |
Double | Dim example# | example = 10# or example = 10R |
Decimal | Dim example@ | example = 10@ or example = 10D |
Char | N/A | example = "A"C |
String | Dim example$ | N/A |
UShort | N/A | example = 10US |
UInteger | N/A | example = 10UI |
ULong | N/A | example = 10UL |
整数后缀也可用于十六进制(&H)或八进制(&O)前缀:
example = &H8000S or example = &O77&
日期(时间)对象也可以使用文字语法定义:
Dim example As Date = #7/26/2016 12:8 PM#
声明变量后,它将存在于声明的包含类型、子或函数的范围内,例如:
Public Function IncrementCounter() As Integer Dim counter As Integer = 0 counter += 1 Return counter 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