Dim 陳述式 (Visual Basic)

宣告並配置一或多個變數的儲存空間。

語法

[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ]
Dim [ WithEvents ] variablelist

組件

  • attributelist

    選擇性。 請參閱屬性清單

  • accessmodifier

    選擇性。 可以是下列其中一項:

    請參閱 Access levels in Visual Basic

  • Shared

    選擇性。 請參閱 Shared

  • Shadows

    選擇性。 請參閱 Shadows

  • Static

    選擇性。 請參閱 Static

  • ReadOnly

    選擇性。 請參閱 ReadOnly

  • WithEvents

    選擇性。 指定這些項目是參考可引發事件類別執行個體的物件變數。 請參閱 WithEvents

  • variablelist

    必要。 此陳述式中宣告的變數清單。

    variable [ , variable ... ]

    每個 variable 都具有下列語法和組件:

    variablename [ ( [ boundslist ] ) ] [ As [ New ] datatype [ With{[ .propertyname = propinitializer [ , ... ] ] } ] ] [ = initializer ]

    部分 描述
    variablename 必要。 變數的名稱。 請參閱 Declared Element Names
    boundslist 選擇性。 陣列變數的每個維度界限清單。
    New 選擇性。 當 Dim 陳述式執行時,便會建立類別的新執行個體。
    datatype 選擇性。 變數的資料類型。
    With 選擇性。 介紹物件初始設定式清單。
    propertyname 選擇性。 您要建立執行個體類別中的屬性名稱。
    propinitializer 必須加在 propertyname = 後面。 評估並指派給屬性名稱的運算式。
    initializer 如果未指定 New,則為選擇性。 在建立時評估並指派給變數的運算式。

備註

Visual Basic 編譯器會使用 Dim 陳述式來判斷變數的資料類型和其他資訊,例如可存取變數的程式碼。 下列範例會宣告變數以保存 Integer 值。

Dim numberOfStudents As Integer

您可指定任何資料類型或列舉、結構、類別或介面的名稱。

Dim finished As Boolean
Dim monitorBox As System.Windows.Forms.Form

針對參考型別,您會使用 New 關鍵字來建立資料類型所指定類別或結構的新執行個體。 如果您使用 New,則不會使用初始設定式運算式。 相反地,如果必要,您會將引數提供給您要從中建立變數的類別建構函式。

Dim bottomLabel As New System.Windows.Forms.Label

您可在程序、區塊、類別、結構或模組中宣告變數。 您無法在來源檔案、命名空間或介面中宣告變數。 如需詳細資訊,請參閱宣告內容和預設存取層級

在任何程序外部,在模組層級宣告的變數為成員變數或欄位。 成員變數的範圍涵蓋類別、結構或模組中。 在程序層級宣告的變數為區域變數。 區域變數的範圍僅涵蓋程序或區塊。

下列存取修飾詞會用於宣告程序外部的變數:PublicProtectedFriendProtected FriendPrivate。 如需詳細資訊,請參閱 Visual Basic 中的存取層級

如果您指定下列任一修飾元,則 Dim 關鍵字為選擇性且通常會省略:PublicProtectedFriendProtected FriendPrivateSharedShadowsStaticReadOnlyWithEvents

Public maximumAllowed As Double
Protected Friend currentUserName As String
Private salary As Decimal
Static runningTotal As Integer

如果 Option Explicit 已開啟 (預設值),編譯器會要求宣告您所使用的每個變數。 如需詳細資訊,請參閱 Option Explicit 陳述式

指定初始值

您可在建立變數後,將值指派給該變數。 針對實值型別,您會使用初始設定式來提供要指派給變數的運算式。 運算式必須評估為可在編譯時間計算的常數。

Dim quantity As Integer = 10
Dim message As String = "Just started"

如果指定初始設定式且在 As 子句中未指定資料類型,則會使用型別推斷從初始設定式推斷資料類型。 在下列範例中,num1num2 的強型別為整數。 在第二個宣告中,型別推斷會從值 3 推斷類型。

' Use explicit typing.
Dim num1 As Integer = 3

' Use local type inference.
Dim num2 = 3

型別推斷適用於程序層級。 型別推斷不適用於類別、結構、模型或介面的程序之外。 如需型別推斷的詳細資訊,請參閱 Option Infer 陳述式區域型別推斷

如需未指定資料類型或初始設定式時發生情況的詳細資訊,請參閱本主題稍後的預設資料類型和值

您可使用物件初始設定式來宣告具名和匿名型別的執行個體。 下列程式碼會建立 Student 類別的執行個體並使用物件初始設定式來初始化屬性。

Dim student1 As New Student With {.First = "Michael",
                                  .Last = "Tucker"}

如需物件初始設定式的詳細資訊,請參閱操作說明:使用物件初始設定式宣告物件物件初始設定式:具名和匿名型別匿名型別

宣告多個變數

您可在一個宣告陳述式中宣告多個變數,並指定每個變數的變數名稱,並在下列每個陣列名稱後面加上括弧。 以逗號分隔多個變數。

Dim lastTime, nextTime, allTimes() As Date

如果您使用一個 As 子句宣告多個變數,則無法提供該變數群組的初始設定式。

您可針對每所宣告的變數使用 As 子句,指定不同變數的不同資料類型。 每個變數會採用第一個 As 子句在其 variablename 組件之後所指定的資料類型。

Dim a, b, c As Single, x, y As Double, i As Integer
' a, b, and c are all Single; x and y are both Double

陣列

您可宣告變數來保存陣列,即可保存多個值。 若要指定變數保存陣列,請緊接著在其 variablename 後面加上括弧。 如需陣列的詳細資訊,請參閱陣列

您可指定每個陣列維度的下限和上限。 若要執行此操作,請在括弧內包含 boundslist。 針對每個維度,boundslist 會指定上限並選擇性指定下限。 不論是否指定,下限一律為零。 每個索引可能為 0 到其上限值不等。

下列兩個陳述式是相等的。 每個陳述式會宣告 21 Integer 個元素的陣列。 存取陣列時,索引可能會為 0 到 20 不等。

Dim totals(20) As Integer
Dim totals(0 To 20) As Integer

下列陳述式會宣告類型 Double 的二維陣列。 陣列各有 4 個列 (3 + 1) 和 6 個欄 (5 + 1)。 請注意,上限表示索引的可能最高值,而不是維度的長度。 維度的長度為加上一的上限。

Dim matrix2(3, 5) As Double

陣列可有 1 到 32 個維度。

您可將陣列宣告中的所有界限保留空白。 如果您如此操作,陣列會有您指定的維度數目而未初始化。 其中有 Nothing 的值,直到您至少初始化一個元素為止。 Dim 陳述式必須指定所有維度或無維度的界限。

' Declare an array with blank array bounds.
Dim messages() As String
' Initialize the array.
ReDim messages(4)

如果陣列有多個維度,您必須在括弧之間包含逗號以指出維度數目。

Dim oneDimension(), twoDimensions(,), threeDimensions(,,) As Byte

您可將其他中一個陣列維度宣告為 -1 以宣告長度為零的陣列。 含有長度為零的陣列變數並不會具有 Nothing 值。 某些通用語言執行平台函式需要長度為零的陣列。 如果嘗試存取這類陣列,就會發生執行階段例外狀況。 如需詳細資訊,請參閱陣列

您可使用陣列常值來初始化陣列的值。 若要值行此操作,請使用大括弧 ({}) 括住初始化值。

Dim longArray() As Long = {0, 1, 2, 3}

針對多維陣列,每個個別維度的初始化會在維度外部以大括弧括住。 元素會依列為主順序進行指定。

Dim twoDimensions(,) As Integer = {{0, 1, 2}, {10, 11, 12}}

如需陣列常值的詳細資訊,請參閱陣列

預設資料類型和值

下表說明在 Dim 陳述式中指定資料類型和初始設定式的各種組合結果。

指定了資料類型? 指定了初始設定式? 範例 結果
No Dim qty 如果 Option Strict 已關閉 (預值值),變數會設定為 Nothing

如果 Option Strict 已開啟,就會發生編譯時間錯誤。
No Yes Dim qty = 5 如果 Option Infer 已開啟 (預設值),此變數會採用初始設定式的資料類型。 請參閱區域型別推斷

如果 Option Infer 已關閉,且 Option Strict 也已關閉,此變數會採用 Object 的資料類型。

如果 Option Infer 已關閉,但是 Option Strict 已開啟,就會發生編譯時間錯誤。
No Dim qty As Integer 變數會初始化為資料類型的預設值。 請參閱本節稍後的表格。
Yes Yes Dim qty As Integer = 5 如果初始設定式的資料類型無法轉換成指定的資料類型,就會發生編譯時期錯誤。

如果您指定資料類型但未指定初始設定式,Visual Basic 會將變數初始化為其資料類型的預設值。 下表顯示預設初始化值。

資料類型 預設值
所有數值型別 (包含 ByteSByte) 0
Char 二進位 0
所有參考型別 (包含 ObjectString 和所有陣列) Nothing
Boolean False
Date 1 年 1 月 1 日上午 12:00 (01/01/0001 12:00:00 AM)

結構的每個元素會視為個別變數進行初始化。 如果您宣告陣列的長度但未初始化其元素,則每個元素會視為個別變數進行初始化。

靜態區域變數存留期

Static 區域變數的存留期大於所宣告程序的存留期。 變數存留期的界限取決於宣告程序的位置和是否為 Shared

程序宣告 變數初始化 變數不再存在
在模組中 初次呼叫程序時 程序停止值型時
在類別或結構中,程序為 Shared 初次對特定執行個體或對類別或結構本身呼叫程序 程序停止值型時
在類別或結構中,程序並非為 Shared 初次對特定執行個體呼叫程序 釋出執行個體以進行記憶體回收 (GC) 時

屬性和修飾元

您僅能將屬性提供給成員變數,而不能提供給區域變數。 屬性會將資訊提供給組件中繼資料,這對暫時儲存區 (例如區域變數) 沒有意義。

在模組層級,您無法使用 Static 修飾元來宣告成員變數。 在程序層級,您無法使用 SharedShadowsReadOnlyWithEvents 或存取修飾詞來宣告區域變數。

您可透過提供 accessmodifier 來指定可存取變數的程式碼。 類別和模組成員變數 (程序外部) 預設為私人存取,結構成員變數預設為公用存取。 您可使用存取修飾詞來調整其存取層級。 您無法在區域變數 (程序內部) 上使用存取修飾詞。

您僅可在成員變數上指定 WithEvents,而不能在程序內部的區域變數上指定。 如果您指定 WithEvents,變數的資料類型必須為指定的類別類型,而不是 Object。 您無法使用 WithEvents 宣告陣列。 如需事件的詳細資訊,請參閱 Events

注意

類別、結構或模組外部的程式碼必須使用類別、結構或模組的名稱限定成員變數的名稱。 程序外部的程式碼或區塊無法參考該程式或區塊內的任何區域變數。

釋放受控資源

.NET 架構記憶體回收行程會處置受控資源,而您無須額外編碼。 不過,您可強制處置受控資源,而不等待記憶體回收行程。

如果類別保存特別有價值且稀少的資源 (例如資料庫連接或檔案控制代碼),您可能不想要等到下一個記憶體回收清除不再使用的類別值型個體。 類別可實作 IDisposable 介面以提供方法,在記憶體回收之前釋放資源。 實作介面的類別會公開 Dispose 方法,您可用於呼叫以強制立即釋放有價值的資源。

Using 陳述式會自動化程序以取得資源、執行一組陳述式,接著處置資源。 不過,資源必須實作 IDisposable 介面。 如需詳細資訊,請參閱 Using 陳述式

範例 1

下列範例搭配使用 Dim 陳述式與各種選項來宣告變數。

' Declare and initialize a Long variable.
Dim startingAmount As Long = 500

' Declare a local variable that always retains its value,
' even after its procedure returns to the calling code.
Static totalSales As Double

' Declare a variable that refers to an array.
Dim highTemperature(31) As Integer

' Declare and initialize an array variable that
' holds four Boolean check values.
Dim checkValues() As Boolean = {False, False, True, False}

範例 2

下列範例會列出介於 1 到 30 之間的質數。 區域變數的範圍會在程式碼註解中描述。

Public Sub ListPrimes()
    ' The sb variable can be accessed only
    ' within the ListPrimes procedure.
    Dim sb As New System.Text.StringBuilder()

    ' The number variable can be accessed only
    ' within the For...Next block.  A different
    ' variable with the same name could be declared
    ' outside of the For...Next block.
    For number As Integer = 1 To 30
        If CheckIfPrime(number) = True Then
            sb.Append(number.ToString & " ")
        End If
    Next

    Debug.WriteLine(sb.ToString)
    ' Output: 2 3 5 7 11 13 17 19 23 29
End Sub

Private Function CheckIfPrime(ByVal number As Integer) As Boolean
    If number < 2 Then
        Return False
    Else
        ' The root and highCheck variables can be accessed
        ' only within the Else block.  Different variables
        ' with the same names could be declared outside of
        ' the Else block.
        Dim root As Double = Math.Sqrt(number)
        Dim highCheck As Integer = Convert.ToInt32(Math.Truncate(root))

        ' The div variable can be accessed only within
        ' the For...Next block.
        For div As Integer = 2 To highCheck
            If number Mod div = 0 Then
                Return False
            End If
        Next

        Return True
    End If
End Function

範例 3

在下列範例中,會在類別層級宣告 speedValue 變數。 Private 關鍵字會用來宣告變數。 Car 類別中的任何程序都可存取變數。

' Create a new instance of a Car.
Dim theCar As New Car()
theCar.Accelerate(30)
theCar.Accelerate(20)
theCar.Accelerate(-5)

Debug.WriteLine(theCar.Speed.ToString)
' Output: 45
Public Class Car
    ' The speedValue variable can be accessed by
    ' any procedure in the Car class.
    Private speedValue As Integer = 0

    Public ReadOnly Property Speed() As Integer
        Get
            Return speedValue
        End Get
    End Property

    Public Sub Accelerate(ByVal speedIncrease As Integer)
        speedValue += speedIncrease
    End Sub
End Class

另請參閱