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

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

語法Syntax

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

組件Parts

選擇性。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 後需要propertyname=。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.

備註Remarks

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 Friend,和PrivateThe 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.

Dim關鍵字是選擇性,而且通常省略 如果您指定任何下列修飾詞: PublicProtectedFriendProtected FriendPrivateSharedShadowsStaticReadOnly,或WithEventsThe 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 Infer 陳述式區域型別推斷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"}

如需物件初始設定式的詳細資訊,請參閱How to:使用物件初始設定式宣告物件物件初始設定式:具名和匿名型別,並匿名型別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. 每個變數會在第一個指定的資料類型As子句後發生其variablename組件。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

陣列Arrays

您可以宣告的變數來保存陣列,其中可包含多個值。You can declare a variable to hold an array, which can hold multiple values. 若要指定變數會保留一個陣列,請遵循其variablename立即使用括號。To 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. 若要這樣做,請包含boundslist在括號內。To do this, include a boundslist inside the parentheses. 每個維度,boundslist指定上限以及選擇性的下限。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. 每個索引從 0 到上限值而有所不同。Each index can vary from zero through its upper bound value.

下列兩個陳述式是相等的。The following two statements are equivalent. 每個陳述式會宣告陣列的 21Integer項目。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

下列陳述式會宣告類型的二維陣列DoubleThe 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. 維度的長度是上限加 1。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. Dim陳述式必須指定所有的維度或的任何維度的界限。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 Infer是 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
所有數字類型 (包括ByteSByte)All 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 AM (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

AStatic區域變數有較長的存留期比宣告它的程序。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.

您可以指定哪些程式碼可以存取的變數,藉由提供accessmodifierYou 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. 您無法宣告陣列WithEventsYou 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.

釋放 Managed 的資源Releasing Managed Resources

.NET Framework 記憶體回收行程會處置 managed 資源而不需要任何額外的程式碼,就在您的組件。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.

Using陳述式自動化程序取得資源、 執行一組陳述式,和然後處置的資源。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.

範例Example

下列範例會藉由宣告變數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}

範例Example

下列範例會列出介於 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
    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

範例Example

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

' 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

另請參閱See also