Dim 陳述式 (Visual Basic)Dim Statement (Visual Basic)

宣告並配置一或多個變數的儲存空間。Declares and allocates storage space for one or more variables.


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


選擇項。Optional. 指定這些是參考可引發事件之類別實例的物件變數。Specifies that these are object variables that refer to instances of a class that can raise events. 請參閱WithEventsSee WithEvents.

  • variablelist

    必要項。Required. 在此語句中宣告的變數清單。List of variables being declared in this statement.

    variable [ , variable ... ]

    每個 variable 都具有下列語法和組件:Each variable has the following syntax and parts:

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

    組件Part 描述Description
    variablename 必要項。Required. 變數的名稱。Name of the variable. 請參閱 Declared Element NamesSee Declared Element Names.
    boundslist 選擇項。Optional. 陣列變數的每個維度的界限清單。List of bounds of each dimension of an array variable.
    New 選擇項。Optional. Dim 語句執行時,建立類別的新實例。Creates a new instance of the class when the Dim statement runs.
    datatype 選擇項。Optional. 變數的資料類型。Data type of the variable.
    With 選擇項。Optional. 引進物件初始化運算式清單。Introduces the object initializer list.
    propertyname 選擇項。Optional. 您要做為實例之類別中的屬性名稱。The name of a property in the class you are making an instance of.
    propinitializer @No__t_0 = 之後才需要。Required after propertyname =. 評估並指派給屬性名稱的運算式。The expression that is evaluated and assigned to the property name.
    initializer 如果未指定 New,則為選擇性。Optional if New is not specified. 建立時,評估並指派給變數的運算式。Expression that is evaluated and assigned to the variable when it is created.


Visual Basic 編譯器會使用 Dim 語句來判斷變數的資料類型和其他資訊,例如可存取變數的程式碼。The Visual Basic compiler uses the Dim statement to determine the variable's data type and other information, such as what code can access the variable. 下列範例會宣告用來保存 Integer 值的變數。The following example declares a variable to hold an Integer value.

Dim numberOfStudents As Integer

您可以指定任何資料類型,或是列舉、結構、類別或介面的名稱。You can specify any data type or the name of an enumeration, structure, class, or interface.

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

對於參考型別,您可以使用 New 關鍵字來建立由資料類型所指定之類別或結構的新實例。For a reference type, you use the New keyword to create a new instance of the class or structure that is specified by the data type. 如果您使用 New,就不會使用初始化運算式運算式。If you use New, you do not use an initializer expression. 相反地,您會提供引數(如有需要)到您要在其中建立變數之類別的函式。Instead, you supply arguments, if they are required, to the constructor of the class from which you are creating the variable.

Dim bottomLabel As New System.Windows.Forms.Label

您可以在程式、區塊、類別、結構或模組中宣告變數。You can declare a variable in a procedure, block, class, structure, or module. 您無法在原始檔、命名空間或介面中宣告變數。You cannot declare a variable in a source file, namespace, or interface. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

在任何程式之外,于模組層級宣告的變數是成員變數欄位A variable that is declared at module level, outside any procedure, is a member variable or field. 成員變數在其類別、結構或模組的範圍內。Member variables are in scope throughout their class, structure, or module. 在程式層級宣告的變數是本機變數A variable that is declared at procedure level is a local variable. 區域變數僅限於其程式或區塊內的範圍。Local variables are in scope only within their procedure or block.

下列存取修飾詞是用來在程式之外宣告變數: PublicProtectedFriendProtected FriendPrivateThe following access modifiers are used to declare variables outside a procedure: Public, Protected, Friend, Protected Friend, and Private. 如需詳細資訊,請參閱Visual Basic 中的存取層級For more information, see Access levels in Visual Basic.

@No__t_0 關鍵字是選擇性的,而且如果您指定下列任何修飾詞,通常會省略: PublicProtectedFriendProtected FriendPrivateSharedShadowsStaticReadOnly 或 0。The Dim keyword is optional and usually omitted if you specify any of the following modifiers: Public, Protected, Friend, Protected Friend, Private, Shared, Shadows, Static, ReadOnly, or WithEvents.

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

如果 Option Explicit 是 on (預設值),則編譯器需要您所使用之每個變數的宣告。If Option Explicit is on (the default), the compiler requires a declaration for every variable you use. 如需詳細資訊,請參閱Option Explicit 語句For more information, see Option Explicit Statement.

指定初始值Specifying an Initial Value

建立變數時,您可以將值指派給它。You can assign a value to a variable when it is created. 對於實值型別,您可以使用初始化運算式來提供要指派給變數的運算式。For a value type, you use an initializer to supply an expression to be assigned to the variable. 運算式必須評估為可在編譯時期計算的常數。The expression must evaluate to a constant that can be calculated at compile time.

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

如果指定了初始化運算式,而且未在 As 子句中指定資料類型,則會使用型別推斷來推斷初始化運算式的資料型別。If an initializer is specified and a data type is not specified in an As clause, type inference is used to infer the data type from the initializer. 在下列範例中,num1num2 都是強型別做為整數。In the following example, both num1 and num2 are strongly typed as integers. 在第二個宣告中,型別推斷會從值3推斷型別。In the second declaration, type inference infers the type from the value 3.

' Use explicit typing.
Dim num1 As Integer = 3

' Use local type inference.
Dim num2 = 3

型別推斷適用于程式層級。Type inference applies at the procedure level. 不適用於類別、結構、模組或介面中的程式之外。It does not apply outside a procedure in a class, structure, module, or interface. 如需型別推斷的詳細資訊,請參閱Option 推斷語句區欄位型別推斷For more information about type inference, see Option Infer Statement and Local Type Inference.

如需未指定資料類型或初始化運算式時,會發生什麼情況的詳細資訊,請參閱本主題稍後的預設資料類型和值For information about what happens when a data type or initializer is not specified, see Default Data Types and Values later in this topic.

您可以使用物件初始化運算式,宣告名為和匿名型別的實例。You can use an object initializer to declare instances of named and anonymous types. 下列程式碼會建立 Student 類別的實例,並使用物件初始化運算式來初始化屬性。The following code creates an instance of a Student class and uses an object initializer to initialize properties.

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

如需物件初始化運算式的詳細資訊,請參閱如何:使用物件初始化運算式宣告物件物件初始化運算式:命名和匿名型別匿名型別For more information about object initializers, see How to: Declare an Object by Using an Object Initializer, Object Initializers: Named and Anonymous Types, and Anonymous Types.

宣告多個變數Declaring Multiple Variables

您可以在一個宣告語句中宣告數個變數,為每一個宣告指定變數名稱,並在每個陣列名稱稱後面加上括弧。You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. 以逗號分隔多個變數。Multiple variables are separated by commas.

Dim lastTime, nextTime, allTimes() As Date

如果您使用一個 As 子句來宣告一個以上的變數,就無法為該變數群組提供初始化運算式。If you declare more than one variable with one As clause, you cannot supply an initializer for that group of variables.

您可以針對您所宣告的每個變數使用個別的 As 子句,為不同的變數指定不同的資料類型。You can specify different data types for different variables by using a separate As clause for each variable you declare. 每個變數都會接受在其 variablename 部分之後遇到的第一個 As 子句中指定的資料類型。Each variable takes the data type specified in the first As clause encountered after its variablename part.

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


您可以宣告變數來保存陣列,其中可以保留多個值。You can declare a variable to hold an array, which can hold multiple values. 若要指定變數保存陣列,請在其後面加上括弧的 variablenameTo specify that a variable holds an array, follow its variablename immediately with parentheses. 如需陣列的詳細資訊,請參閱陣列For more information about arrays, see Arrays.

您可以指定陣列的每個維度的下限和上限。You can specify the lower and upper bound of each dimension of an array. 若要這麼做,請在括弧內包含 boundslistTo do this, include a boundslist inside the parentheses. @No__t_0 指定每個維度的上限和下限。For each dimension, the boundslist specifies the upper bound and optionally the lower bound. 下限一律為零,不論您是否指定。The lower bound is always zero, whether you specify it or not. 每個索引的上限值可能會從零開始。Each index can vary from zero through its upper bound value.

下列兩個語句是相等的。The following two statements are equivalent. 每個語句都會宣告21個 Integer 元素的陣列。Each statement declares an array of 21 Integer elements. 當您存取陣列時,索引可能會從0到20。When you access the array, the index can vary from 0 through 20.

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

下列語句會宣告 Double 類型的二維陣列。The following statement declares a two-dimensional array of type Double. 陣列有4個數據列(3 + 1),分別為6個數據行(5 + 1)。The array has 4 rows (3 + 1) of 6 columns (5 + 1) each. 請注意,上限代表索引的最大可能值,而不是維度的長度。Note that an upper bound represents the highest possible value for the index, not the length of the dimension. 維度的長度是上限加一。The length of the dimension is the upper bound plus one.

Dim matrix2(3, 5) As Double

陣列可以有1到32個維度。An array can have from 1 to 32 dimensions.

您可以在陣列宣告中將所有界限保留空白。You can leave all the bounds blank in an array declaration. 如果您這樣做,陣列就會包含您指定的維度數目,但它是未初始化的。If you do this, the array has the number of dimensions you specify, but it is uninitialized. 它的值為 Nothing,直到您至少初始化其中的部分元素為止。It has a value of Nothing until you initialize at least some of its elements. @No__t_0 語句必須為所有維度或沒有維度指定界限。The Dim statement must specify bounds either for all dimensions or for no dimensions.

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

如果陣列有多個維度,您必須在括弧之間包含逗號,以指示維度的數目。If the array has more than one dimension, you must include commas between the parentheses to indicate the number of dimensions.

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

您可以宣告陣列的其中一個維度為-1,以宣告長度為零的陣列You can declare a zero-length array by declaring one of the array's dimensions to be -1. 持有長度為零之陣列的變數沒有值 NothingA variable that holds a zero-length array does not have the value Nothing. 特定的 common language runtime 函式需要長度為零的陣列。Zero-length arrays are required by certain common language runtime functions. 如果您嘗試存取這類陣列,就會發生執行時間例外狀況。If you try to access such an array, a runtime exception occurs. 如需詳細資訊,請參閱陣列For more information, see Arrays.

您可以使用陣列常值來初始化陣列的值。You can initialize the values of an array by using an array literal. 若要這麼做,請使用大括弧({})來括住初始化值。To do this, surround the initialization values with braces ({}).

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

若是多維陣列,每個不同維度的初始化都會以大括弧括住在外部維度中。For multidimensional arrays, the initialization for each separate dimension is enclosed in braces in the outer dimension. 元素會以資料列主要順序來指定。The elements are specified in row-major order.

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

如需陣列常值的詳細資訊,請參閱陣列For more information about array literals, see Arrays.

預設資料類型和值Default Data Types and Values

下表說明在 Dim 陳述式中指定資料類型和初始設定式的各種組合結果。The following table describes the results of various combinations of specifying the data type and initializer in a Dim statement.

指定了資料類型?Data type specified? 指定了初始設定式?Initializer specified? 範例Example 結果Result
No No Dim qty 如果Option Strict為 off (預設值),則變數會設定為 NothingIf Option Strict is off (the default), the variable is set to Nothing.

如果 Option Strict 已開啟,就會發生編譯時間錯誤。If Option Strict is on, a compile-time error occurs.
No [是]Yes Dim qty = 5 如果Option 推斷為 on (預設值),則變數會採用初始化運算式的資料類型。If Option Infer is on (the default), the variable takes the data type of the initializer. 請參閱區欄位型別推斷See Local Type Inference.

如果 Option Infer 已關閉,且 Option Strict 也已關閉,此變數會採用 Object 的資料類型。If Option Infer is off and Option Strict is off, the variable takes the data type of Object.

如果 Option Infer 已關閉,但是 Option Strict 已開啟,就會發生編譯時間錯誤。If Option Infer is off and Option Strict is on, a compile-time error occurs.
[是]Yes No Dim qty As Integer 變數會初始化為資料類型的預設值。The variable is initialized to the default value for the data type. 請參閱本節稍後的表格。See the table later in this section.
[是]Yes [是]Yes Dim qty As Integer = 5 如果初始設定式的資料類型無法轉換成指定的資料類型,就會發生編譯時期錯誤。If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs.

如果您指定資料類型,但未指定初始化運算式,Visual Basic 會將變數初始化為其資料類型的預設值。If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type. 下表顯示預設的初始化值。The following table shows the default initialization values.

資料類型Data type 預設值Default value
所有數數值型別(包括 ByteSByteAll numeric types (including Byte and SByte) 00
Char 二進位0Binary 0
所有參考型別(包括 ObjectString 和所有陣列)All reference types (including Object, String, and all arrays) Nothing
Boolean False
Date 每年1月1日上午12:00 (01/01/0001 12:00:00 AM)12:00 AM of January 1 of the year 1 (01/01/0001 12:00:00 AM)

結構的每個元素都會初始化為另一個變數。Each element of a structure is initialized as if it were a separate variable. 如果您宣告陣列的長度,但不初始化其元素,則每個專案都會初始化為個別的變數。If you declare the length of an array but do not initialize its elements, each element is initialized as if it were a separate variable.

靜態區域變數存留期Static Local Variable Lifetime

@No__t_0 本機變數的存留期比宣告它的程式還長。A Static local variable has a longer lifetime than that of the procedure in which it is declared. 變數存留期的界限取決於程式的宣告位置,以及是否 SharedThe boundaries of the variable's lifetime depend on where the procedure is declared and whether it is Shared.

過程聲明Procedure declaration 變數已初始化Variable initialized 變數停止現有的Variable stops existing
在模組中In a module 第一次呼叫程式時The first time the procedure is called 當程式停止執行時When your program stops execution
在類別或結構中,程式是 SharedIn a class or structure, procedure is Shared 第一次在特定實例或類別或結構本身上呼叫程式時The first time the procedure is called either on a specific instance or on the class or structure itself 當程式停止執行時When your program stops execution
在類別或結構中,程式不 SharedIn a class or structure, procedure isn't Shared 第一次在特定實例上呼叫程式時The first time the procedure is called on a specific instance 釋放實例以進行垃圾收集(GC)時When the instance is released for garbage collection (GC)

屬性和修飾詞Attributes and Modifiers

您只能將屬性套用至成員變數,而不能套用至本機變數。You can apply attributes only to member variables, not to local variables. 屬性會將資訊提供給元件的中繼資料,這對暫存儲存體(例如區域變數)沒有意義。An attribute contributes information to the assembly's metadata, which is not meaningful for temporary storage such as local variables.

在模組層級,您無法使用 Static 修飾詞來宣告成員變數。At module level, you cannot use the Static modifier to declare member variables. 在程式層級上,您不能使用 SharedShadowsReadOnlyWithEvents 或任何存取修飾詞來宣告本機變數。At procedure level, you cannot use Shared, Shadows, ReadOnly, WithEvents, or any access modifiers to declare local variables.

您可以藉由提供 accessmodifier,指定可以存取變數的程式碼。You can specify what code can access a variable by supplying an accessmodifier. 類別和模組成員變數(在任何程式之外)預設為私用存取,而結構成員變數預設為公用存取。Class and module member variables (outside any procedure) default to private access, and structure member variables default to public access. 您可以使用存取修飾詞來調整其存取層級。You can adjust their access levels with the access modifiers. 您不能在本機變數上使用存取修飾詞(在程式內)。You cannot use access modifiers on local variables (inside a procedure).

您只能在成員變數上指定 WithEvents,而不是在程式內的區域變數上指定。You can specify WithEvents only on member variables, not on local variables inside a procedure. 如果您指定 WithEvents,變數的資料類型必須是特定的類別類型,而不是 ObjectIf you specify WithEvents, the data type of the variable must be a specific class type, not Object. 您無法使用 WithEvents 宣告陣列。You cannot declare an array with WithEvents. 如需事件的詳細資訊,請參閱事件For more information about events, see Events.


類別、結構或模組之外的程式碼必須使用該類別、結構或模組的名稱來限定成員變數的名稱。Code outside a class, structure, or module must qualify a member variable's name with the name of that class, structure, or module. 程式或區塊外的程式碼無法參考該程式或區塊中的任何區域變數。Code outside a procedure or block cannot refer to any local variables within that procedure or block.

釋放受控資源Releasing Managed Resources

.NET Framework 垃圾收集行程會處置受控資源,而不需任何額外的程式碼。The .NET Framework garbage collector disposes of managed resources without any extra coding on your part. 不過,您可以強制處置受管理的資源,而不是等候垃圾收集行程。However, you can force the disposal of a managed resource instead of waiting for the garbage collector.

如果類別持有特別寶貴的資源(例如資料庫連接或檔案控制代碼),您可能不想要等到下一次垃圾收集,就能清除不再使用的類別實例。If a class holds onto a particularly valuable and scarce resource (such as a database connection or file handle), you might not want to wait until the next garbage collection to clean up a class instance that's no longer in use. 類別可以執行 IDisposable 介面,以提供在垃圾收集之前釋放資源的方式。A class may implement the IDisposable interface to provide a way to release resources before a garbage collection. 實作為介面的類別會公開可呼叫的 Dispose 方法,以強制立即釋放寶貴的資源。A class that implements that interface exposes a Dispose method that can be called to force valuable resources to be released immediately.

@No__t_0 語句會自動化取得資源、執行一組語句,然後處置資源的程式。The Using statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. 不過,資源必須執行 IDisposable 介面。However, the resource must implement the IDisposable interface. 如需詳細資訊,請參閱 Using 陳述式For more information, see Using Statement.


下列範例會使用 Dim 語句搭配各種選項來宣告變數。The following example declares variables by using the Dim statement with various options.

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

' Declare a variable that refers to a Button object,
' create a Button object, and assign the Button object
' to the variable.
Dim switchButton As New System.Windows.Forms.Button

' 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}


下列範例會列出介於1到30之間的質數。The following example lists the prime numbers between 1 and 30. 本機變數的範圍會在程式碼批註中說明。The scope of local variables is described in code comments.

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

    ' 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
        ' 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

        Return True
    End If
End Function


在下列範例中,會在類別層級宣告 speedValue 變數。In the following example, the speedValue variable is declared at the class level. @No__t_0 關鍵字是用來宣告變數。The Private keyword is used to declare the variable. @No__t_0 類別中的任何程式都可以存取變數。The variable can be accessed by any procedure in the Car class.

' Create a new instance of a Car.
Dim theCar As New Car()

' 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
            Return speedValue
        End Get
    End Property

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

請參閱See also