使用基本型別宣告和分配變數

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