Visual Basic 中的陣列Arrays in Visual Basic

陣列是一組值,都稱為項目,以邏輯方式彼此相關。An array is a set of values, which are termed elements, that are logically related to each other. 例如,陣列可能包含中含有文法學校中; 每一年級學生數目陣列的每個項目是單一的年級的學生數目。For example, an array may consist of the number of students in each grade in a grammar school; each element of the array is the number of students in a single grade. 同樣地,陣列可能包含學生的成績類別;陣列的每個項目是一個單一的等級。Similarly, an array may consist of a student's grades for a class; each element of the array is a single grade.

這是可能的個別變數,以儲存每個資料項目。It is possible individual variables to store each of our data items. 例如,如果我們的應用程式分析學生成績,我們可以使用個別的變數的每個學生的成績等級,例如englishGrade1englishGrade2等等。這個方法有三個主要限制:For example, if our application analyzes student grades, we can use a separate variable for each student's grade, such as englishGrade1, englishGrade2, etc. This approach has three major limitations:

  • 我們必須在執行階段知道我們必須處理正好多少成績。We have to know at design time exactly how many grades we have to handle.
  • 快速處理大量的等級會變得不便。Handling large numbers of grades quickly becomes unwieldy. 接著,這可讓應用程式很有可能有嚴重的錯誤。This in turn makes an application much more likely to have serious bugs.
  • 很難維護。It is difficult to maintain. 我們將新增的每個新級需要應用程式可修改、 重新編譯和重新部署。Each new grade that we add requires that the application be modified, recompiled, and redeployed.

藉由使用陣列,您可以參考相同的名稱,這些相關的值,並使用數字,稱為index註標來識別個別的項目,根據在陣列中的位置。By using an array, you can refer to these related values by the same name, and use a number that’s called an index or subscript to identify an individual element based on its position in the array. 陣列範圍從 0 到小於陣列中的項目總數的索引。The indexes of an array range from 0 to one less than the total number of elements in the array. 當您使用 Visual Basic 語法定義陣列的大小時,您會指定其最高的索引,不在陣列中的項目總數。When you use Visual Basic syntax to define the size of an array, you specify its highest index, not the total number of elements in the array. 您可以使用將陣列視為一個單位,而且能夠逐一查看其項目可讓您不需要知道確切多少項目包含在設計階段。You can work with the array as a unit, and the ability to iterate its elements frees you from needing to know exactly how many elements it contains at design time.

開始說明前,先提供一些簡單的範例:Some quick examples before explanation:

' Declare a single-dimension array of 5 numbers.
Dim numbers(4) As Integer

' Declare a single-dimension array and set its 4 values.
Dim numbers = New Integer() {1, 2, 4, 8}

' Change the size of an existing array to 16 elements and retain the current values.
ReDim Preserve numbers(15)

' Redefine the size of an existing array and reset the values.
ReDim numbers(15)

' Declare a 6 x 6 multidimensional array.
Dim matrix(5, 5) As Double

' Declare a 4 x 3 multidimensional array and set array element values.
Dim matrix = New Integer(3, 2) {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}}

' Declare a jagged array
Dim sales()() As Double = New Double(11)() {}

簡單陣列中的陣列項目Array elements in a simple array

讓我們建立名為陣列students儲存含有文法學校中每一年級的學生數目。Let's create an array named students to store the number of students in each grade in a grammar school. 項目的索引範圍從 0 到 6。The indexes of the elements range from 0 through 6. 使用這個陣列是簡單較宣告七個變數。Using this array is simpler than declaring seven variables.

下圖顯示students陣列。The following illustration shows the students array. 對於陣列的每一項目︰For each element of the array:

  • 項目的索引代表年級 (索引 0 代表幼稚園)。The index of the element represents the grade (index 0 represents kindergarten).

  • 項目包含的值代表該年級的學生數目。The value that’s contained in the element represents the number of students in that grade.

此圖顯示學生人數的陣列

下列範例包含建立及使用陣列的 Visual Basic 程式碼:The following example contains the Visual Basic code that creates and uses the array:


Module SimpleArray
   Public Sub Main()
      ' Declare an array with 7 elements.
      Dim students(6) As Integer

      ' Assign values to each element.
      students(0) = 23
      students(1) = 19
      students(2) = 21
      students(3) = 17
      students(4) = 19
      students(5) = 20
      students(6) = 22
      
      ' Display the value of each element.
      For ctr As Integer = 0 To 6
         Dim grade As String = If(ctr = 0, "kindergarten", $"grade {ctr}")
         Console.WriteLine($"Students in {grade}: {students(ctr)}")
      Next
   End Sub
End Module
' The example displays the following output:
'     Students in kindergarten: 23
'     Students in grade 1: 19
'     Students in grade 2: 21
'     Students in grade 3: 17
'     Students in grade 4: 19
'     Students in grade 5: 20
'     Students in grade 6: 22

此範例會執行三件事:The example does three things:

  • 它會宣告students七個元素的陣列。It declares a students array with seven elements. 數字6陣列中的宣告表示陣列中的最後一個索引,而其中一個陣列中的項目數大於或等於。The number 6 in the array declaration indicates the last index in the array; it is one less than the number of elements in the array.
  • 它會將值指派到陣列中每個項目。It assigns values to each element in the array. 陣列元素存取使用陣列名稱,並包括括號括住的個別項目的索引。Array elements are accessed by using the array name and including the index of the individual element in parentheses.
  • 它會列出每個值的陣列。It lists each value of the array. 此範例會使用 For 陳述式來存取陣列的每個項目依其索引編號。The example uses a For statement to access each element of the array by its index number.

students在上述範例中的陣列是一維陣列,因為它會使用一個索引。The students array in the preceding example is a one-dimensional array because it uses one index. 陣列,其中會使用一個以上的索引或註標稱為多維度An array that uses more than one index or subscript is called multidimensional. 如需詳細資訊,請參閱本文的其餘部分並Array Dimensions in Visual BasicFor more information, see the rest of this article and Array Dimensions in Visual Basic.

建立陣列Creating an array

您可以定義陣列的大小,以數種方式:You can define the size of an array in several ways:

  • 宣告陣列時,您可以指定大小:You can specify the size when the array is declared:

    ' Declare an array with 10 elements.
    Dim cargoWeights(9) As Double               
    ' Declare a 24 x 2 array.
    Dim hourlyTemperatures(23, 1) As Integer
    ' Declare a jagged array with 31 elements.
    Dim januaryInquiries(30)() As String
    
  • 您可以使用New子句提供陣列的大小,會在建立時:You can use a New clause to supply the size of an array when it’s created:

    ' Declare an array with 10 elements.
    Dim cargoWeights(9) As Double
    ' Declare a 24 x 2 array.
    Dim hourlyTemperatures(23, 1) As Integer
    ' Declare a jagged array with 31 elements. 
    Dim januaryInquiries(30)() As String
    

如果您有現有的陣列,您可以重新定義其大小所使用 ReDim 陳述式。If you have an existing array, you can redefine its size by using the ReDim statement. 您可以指定ReDim陳述式保留陣列中的值,或您可以指定它建立的空陣列。You can specify that the ReDim statement keep the values that are in the array, or you can specify that it create an empty array. 下列範例顯示 ReDim 陳述式的不同使用方法,以修改現有陣列的大小。The following example shows different uses of the ReDim statement to modify the size of an existing array.

' Assign a new array size and retain the current values.
ReDim Preserve cargoWeights(20)
' Assign a new array size and retain only the first five values.
ReDim Preserve cargoWeights(4)
' Assign a new array size and discard all current element values.
ReDim cargoWeights(15)

如需詳細資訊,請參閱 < ReDim 陳述式For more information, see the ReDim Statement.

陣列中儲存值Storing values in an array

您可以使用類型為 Integer的索引來存取陣列中的每一個位置。You can access each location in an array by using an index of type Integer. 使用括弧內的陣列索引即可參照各陣列的位置,從而儲存並擷取陣列中的值。You can store and retrieve values in an array by referencing each array location by using its index enclosed in parentheses. 多維陣列的索引是以逗號 (,) 分隔。Indexes for multidimensional arrays are separated by commas (,). 各個陣列維度皆需一個索引。You need one index for each array dimension.

下列範例顯示一些儲存和擷取值,在陣列中的陳述式。The following example shows some statements that store and retrieve values in arrays.


Module Example
   Public Sub Main()
      ' Create a 10-element integer array.
      Dim numbers(9) As Integer
      Dim value As Integer = 2
        
      ' Write values to it.
      For ctr As Integer = 0 To 9
         numbers(ctr) = value
         value *= 2
      Next
        
      ' Read and sum the array values.  
      Dim sum As Integer
      For ctr As Integer = 0 To 9
         sum += numbers(ctr)
      Next
      Console.WriteLine($"The sum of the values is {sum:N0}")
    End Sub
End Module
' The example displays the following output:
'     The sum of the values is 2,046

陣列常值在陣列填入Populating an array with array literals

藉由使用陣列常值,您可以在同一時間建立填入一組初始的值陣列。By using an array literal, you can populate an array with an initial set of values at the same time that you create it. 陣列常值由大括弧 ({}) 括住的逗點分隔值清單構成。An array literal consists of a list of comma-separated values that are enclosed in braces ({}).

當您使用陣列常值來建立陣列時,可以提供陣列類型,或者使用類型推斷來判別陣列類型。When you create an array by using an array literal, you can either supply the array type or use type inference to determine the array type. 下列範例會示範這兩個選項。The following example shows both options.

' Array literals with explicit type definition.
Dim numbers = New Integer() {1, 2, 4, 8}
' Array literals with type inference.
Dim doubles = {1.5, 2, 9.9, 18}
' Array literals with explicit type definition.
Dim articles() As String = { "the", "a", "an" }

' Array literals with explicit widening type definition.
Dim values() As Double = { 1, 2, 3, 4, 5 }

當您使用型別推斷時,陣列的類型取決於主類型常值的清單中。When you use type inference, the type of the array is determined by the dominant type in the list of literal values. 主控項的型別是陣列中的所有其他類型可以將加寬的型別。The dominant type is the type to which all other types in the array can widen. 如果無法決定此唯一類型,則主類型將成為陣列中其他類型皆可縮小而成的唯一類型。If this unique type can’t be determined, the dominant type is the unique type to which all other types in the array can narrow. 如果這些類型皆無法決定,則主類型為 ObjectIf neither of these unique types can be determined, the dominant type is Object. 例如,如果提供給陣列常值的值清單含有類型值 IntegerLongDouble,則結果陣列的類型是 DoubleFor example, if the list of values that’s supplied to the array literal contains values of type Integer, Long, and Double, the resulting array is of type Double. 因為IntegerLong只會擴展為DoubleDouble是主類型。Because Integer and Long widen only to Double, Double is the dominant type. 如需詳細資訊,請參閱 Widening and Narrowing ConversionsFor more information, see Widening and Narrowing Conversions.

注意

您可以使用型別推斷,只對定義為型別成員中的本機變數的陣列。You can use type inference only for arrays that are defined as local variables in a type member. 如果沒有明確的類型定義,定義在類別層級的陣列常值的陣列都屬於型別Object[]If an explicit type definition is absent, arrays defined with array literals at the class level are of type Object[]. 如需詳細資訊,請參閱 < 區域型別推斷For more information, see Local type inference.

請注意,前一個範例會定義values的型別陣列Double即使所有陣列常值型別的IntegerNote that the previous example defines values as an array of type Double even though all the array literals are of type Integer. 您可以建立此陣列,因為陣列常值中的值可以擴展為Double值。You can create this array because the values in the array literal can widen to Double values.

您也可以建立及使用填入的多維陣列巢狀陣列常值You can also create and populate a multidimensional array by using nested array literals. 巢狀的陣列常值必須是結果陣列一致維度的數目。Nested array literals must have a number of dimensions that’s consistent with the resulting array. 下列範例會使用巢狀的陣列常值建立整數的二維陣列。The following example creates a two-dimensional array of integers by using nested array literals.

' Create and populate a 2 x 2 array.
Dim grid1 = {{1, 2}, {3, 4}}
' Create and populate a 2 x 2 array with 3 elements.
Dim grid2(,) = {{1, 2}, {3, 4}, {5, 6}}

當使用巢狀的陣列常值來建立和填入的陣列,如果巢狀的陣列常值中的項目數不相符,也會發生錯誤。When using nested array literals to create and populate an array, an error occurs if the number of elements in the nested array literals don't match. 如果您明確宣告陣列變數,以比陣列常值的維度數目不同,也會發生錯誤。An error also occurs if you explicitly declare the array variable to have a different number of dimensions than the array literals.

正如同您可以一維陣列,您可以依賴類型推斷使用巢狀的陣列常值建立多維陣列時。Just as you can for one-dimensional arrays, you can rely on type inference when creating a multidimensional array with nested array literals. 推斷的型別是所有的巢狀層級的所有陣列常值中的所有值的主類型。The inferred type is the dominant type for all the values in all the array literals for all nesting level. 下列範例會建立二維陣列型別的Double[,]類型的值從IntegerDoubleThe following example creates a two-dimensional array of type Double[,] from values that are of type Integer and Double.

Dim arr = {{1, 2.0}, {3, 4}, {5, 6}, {7, 8}}

如需其他範例,請參閱How to:初始化陣列變數在 Visual Basic 中的For additional examples, see How to: Initialize an Array Variable in Visual Basic.

逐一查看陣列Iterating through an array

當您逐一查看陣列時,您存取陣列中的每個項目從最低到最高的索引,或從最高到最低。When you iterate through an array, you access each element in the array from the lowest index to the highest or from the highest to the lowest. 一般而言,使用For...下一個陳述式每個...下一個陳述式來逐一查看陣列的元素。Typically, use either the For...Next Statement or the For Each...Next Statement to iterate through the elements of an array. 當您不知道陣列的上限時,您可以呼叫Array.GetUpperBound方法來取得索引的最大值。When you don't know the upper bounds of the array, you can call the Array.GetUpperBound method to get the highest value of the index. 雖然最小的索引值幾乎一律為 0,您就可以呼叫Array.GetLowerBound方法來取得索引的最小值。Although lowest index value is almost always 0, you can call the Array.GetLowerBound method to get the lowest value of the index.

下列範例使用會逐一一維陣列 For...Next 陳述式。The following example iterates through a one-dimensional array by using the For...Next statement.


Module IterateArray
   Public Sub Main()
      Dim numbers = {10, 20, 30}

      For index = 0 To numbers.GetUpperBound(0)
         Console.WriteLine(numbers(index))
      Next
   End Sub
End Module
' The example displays the following output:
'  10
'  20
'  30

下列範例使用會逐一多維陣列 For...Next 陳述式。The following example iterates through a multidimensional array by using a For...Next statement. GetUpperBound 方法具有可指定維度的參數。The GetUpperBound method has a parameter that specifies the dimension. GetUpperBound(0) 傳回第一個維度中,最高的索引和GetUpperBound(1)傳回第二個維度的最高的索引。GetUpperBound(0) returns the highest index of the first dimension, and GetUpperBound(1) returns the highest index of the second dimension.


Module IterateArray
   Public Sub Main()
      Dim numbers = {{1, 2}, {3, 4}, {5, 6}}

      For index0 = 0 To numbers.GetUpperBound(0)
         For index1 = 0 To numbers.GetUpperBound(1)
            Console.Write($"{numbers(index0, index1)} ")
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
' Output 
'  1 2 
'  3 4 
'  5 6

下列範例會使用每個...下一個陳述式來逐一查看一維陣列和二維陣列。The following example uses a For Each...Next Statementto iterate through a one-dimensional array and a two-dimensional array.


Module IterateWithForEach
   Public Sub Main()
      ' Declare and iterate through a one-dimensional array.
      Dim numbers1 = {10, 20, 30}
      
      For Each number In numbers1
         Console.WriteLine(number)
      Next
      Console.WriteLine()
      
      Dim numbers = {{1, 2}, {3, 4}, {5, 6}}

      For Each number In numbers
         Console.WriteLine(number)
      Next
   End Sub
End Module
' The example displays the following output:
'  10
'  20
'  30
'
'  1
'  2
'  3
'  4
'  5
'  6

陣列大小Array size

陣列大小為其所有維度長度之乘積。The size of an array is the product of the lengths of all its dimensions. 它代表目前包含於陣列中的項目總數。It represents the total number of elements currently contained in the array. 例如,下列範例會宣告具有四個元素,每個維度中的 2 維度陣列。For example, the following example declares a 2-dimensional array with four elements in each dimension. 如範例輸出所示,陣列的大小為 16 (或 (3 + 1) * (3 + 1)。As the output from the example shows, the array's size is 16 (or (3 + 1) * (3 + 1).


Module Example
   Public Sub Main()
      Dim arr(3, 3) As Integer
      Console.WriteLine(arr.Length)     
   End Sub
End Module
' The example displays the following output:
'     16

注意

本討論中陣列的大小不適用於不規則陣列。This discussion of array size does not apply to jagged arrays. 如需不規則的陣列和決定不規則陣列的大小,請參閱 < 不規則陣列一節。For information on jagged arrays and determining the size of a jagged array, see the Jagged arrays section.

您可以使用 Array.Length 屬性來尋找陣列的大小。You can find the size of an array by using the Array.Length property. 您可以使用來尋找多維陣列中的每個維度的長度Array.GetLength方法。You can find the length of each dimension of a multidimensional array by using the Array.GetLength method.

指派新的陣列物件,或使用,您可以調整大小的陣列變數ReDim陳述式陳述式。You can resize an array variable by assigning a new array object to it or by using the ReDim Statement statement. 下列範例會使用ReDim陳述式來變更到 51 個元素陣列的 100 個元素的陣列。The following example uses the ReDim statement to change a 100-element array to a 51-element array.


Module Example
   Public Sub Main()
      Dim arr(99) As Integer
      Console.WriteLine(arr.Length)
      
      Redim arr(50)
      Console.WriteLine(arr.Length)
   End Sub
End Module
' The example displays the following output:
'     100
'     51

 

處理陣列大小時,請注意幾點︰There are several things to keep in mind when dealing with the size of an array.

維度長度Dimension Length 每個維度的索引是以 0 為基礎,這表示其範圍從 0 到它的上限。The index of each dimension is 0-based, which means it ranges from 0 to its upper bound. 因此,指定維度的長度是一必須大於該維度的宣告上限。Therefore, the length of a given dimension is one greater than the declared upper bound of that dimension.
長度限制Length Limits 陣列的每個維度的長度是限制的最大值為Integer資料類型,這是Int32.MaxValue或 (2 ^31)-1。The length of every dimension of an array is limited to the maximum value of the Integer data type, which is Int32.MaxValue or (2 ^ 31) - 1. 然而,陣列之總大小也同時受限於系統可用的記憶體。However, the total size of an array is also limited by the memory available on your system. 如果您嘗試將初始化陣列超過可用記憶體數量、 執行階段會擲回OutOfMemoryExceptionIf you attempt to initialize an array that exceeds the amount of available memory, the runtime throws an OutOfMemoryException.
大小及項目大小Size and Element Size 陣列大小與其項目的資料類型無關。An array's size is independent of the data type of its elements. 大小一律是指項目,不,它們會消耗記憶體中的位元組數字總數。The size always represents the total number of elements, not the number of bytes that they consume in memory.
記憶體消耗量Memory Consumption 對陣列在記憶體中的儲存方式做任何假設都是不安全的。It is not safe to make any assumptions regarding how an array is stored in memory. 儲存體會因不同資料寬度的平台而有差異,所以相同陣列於 64 位元系統上所佔記憶體將較 32 位元系統來的多。Storage varies on platforms of different data widths, so the same array can consume more memory on a 64-bit system than on a 32-bit system. 當您初始化陣列時,隨著系統組態不同,通用語言執行平台 (CLR) 會指派儲存體盡可能將項目存放在一起,或是根據實體硬體界限全部加以調整。Depending on system configuration when you initialize an array, the common language runtime (CLR) can assign storage either to pack elements as close together as possible, or to align them all on natural hardware boundaries. 同時,陣列需要耗用儲存體以供其控制資訊使用,此消耗量會隨著維度增加而增加。Also, an array requires a storage overhead for its control information, and this overhead increases with each added dimension.

陣列類型The array type

每個陣列有不同於其項目的資料類型的資料類型。Every array has a data type, which differs from the data type of its elements. 沒有任何單一的資料類型適用於所有的陣列。There is no single data type for all arrays. 陣列的類型反而是由陣列的維度數目,或稱為 「順位」 (rank) 以及陣列項目的資料類型所決定。Instead, the data type of an array is determined by the number of dimensions, or rank, of the array, and the data type of the elements in the array. 兩個陣列變數屬於相同的資料類型具有相同的陣序規範,其項目包含相同的資料類型。Two array variables are of the same data type only when they have the same rank and their elements have the same data type. 陣列的維度的長度不會影響陣列資料型別。The lengths of the dimensions of an array do not influence the array data type.

每個陣列都繼承自 System.Array 類別,而您可以將變數宣告為類型 Array,但不能建立類型為 Array 的陣列。Every array inherits from the System.Array class, and you can declare a variable to be of type Array, but you cannot create an array of type Array. 比方說,雖然下列程式碼會宣告arr類型的變數Array,並呼叫Array.CreateInstance方法具現化的陣列,陣列的型別證實是 Object []。For example, although the following code declares the arr variable to be of type Array and calls the Array.CreateInstance method to instantiate the array, the array's type proves to be Object[].


Module Example
   Public Sub Main()
      Dim arr As Array = Array.CreateInstance(GetType(Object), 19)
      Console.WriteLine(arr.Length)
      Console.WriteLine(arr.GetType().Name)
   End Sub
End Module
' The example displays the following output:
'     19
'     Object[]

此外,ReDim 陳述式無法在宣告為 Array 型別的變數上運作。Also, the ReDim Statement cannot operate on a variable declared as type Array. 基於這些理由,以及型別安全,建議您最好以宣告為特定類型的每個陣列。For these reasons, and for type safety, it is advisable to declare every array as a specific type.

有幾個方法可以找出陣列或其項目的資料類型。You can find out the data type of either an array or its elements in several ways.

  • 您可以呼叫GetType方法來取得變數Type物件,表示變數的執行階段型別。You can call the GetType method on the variable to get a Type object that represents the run-time type of the variable. Type 物件在其屬性和方法中保留了大量的資訊。The Type object holds extensive information in its properties and methods.
  • 您可以將變數傳遞給TypeName函式可取得String的執行階段類型名稱。You can pass the variable to the TypeName function to get a String with the name of run-time type.

下列範例會呼叫二者GetType方法和TypeName函式來判斷陣列的類型。The following example calls the both the GetType method and the TypeName function to determine the type of an array. 陣列型別是Byte(,)The array type is Byte(,). 請注意,Type.BaseType屬性也會指出的位元組陣列的基底類型是Array類別。Note that the Type.BaseType property also indicates that the base type of the byte array is the Array class.


Module Example
   Public Sub Main()
      Dim bytes(9,9) As Byte
      Console.WriteLine($"Type of {nameof(bytes)} array: {bytes.GetType().Name}")
      Console.WriteLine($"Base class of {nameof(bytes)}: {bytes.GetType().BaseType.Name}")
      Console.WriteLine()
      Console.WriteLine($"Type of {nameof(bytes)} array: {TypeName(bytes)}")
   End Sub
End Module
' The example displays the following output:
' Type of bytes array: Byte[,]
' Base class of bytes: Array
' 
' Type of bytes array: Byte(,)


做為傳回值和參數陣列Arrays as return values and parameters

若要從 Function 程序傳回陣列,請將陣列資料型別和維度數目指定為 Function 陳述式的傳回型別。To return an array from a Function procedure, specify the array data type and the number of dimensions as the return type of the Function Statement. 在該函式內,使用相同的資料類型和維度數目來宣告區域陣列變數。Within the function, declare a local array variable with same data type and number of dimensions. Return 陳述式中,包含沒有括弧的區域陣列變數。In the Return Statement, include the local array variable without parentheses.

若要將陣列指定為 Sub 程序或 Function 程序的參數,請為參數定義所指定的資料類型和維度數目。To specify an array as a parameter to a Sub or Function procedure, define the parameter as an array with a specified data type and number of dimensions. 在程序的呼叫,傳遞相同的資料類型和維度數目的陣列變數。In the call to the procedure, pass an array variable with the same data type and number of dimensions.

在下列範例中,GetNumbers函式會傳回Integer(),類型的一維陣列IntegerIn the following example, the GetNumbers function returns an Integer(), a one-dimensional array of type Integer. ShowNumbers 程序接受 Integer() 引數。The ShowNumbers procedure accepts an Integer() argument.


Module ReturnValuesAndParams
   Public Sub Main()
      Dim numbers As Integer() = GetNumbers()
      ShowNumbers(numbers)
   End Sub

   Private Function GetNumbers() As Integer()
      Dim numbers As Integer() = {10, 20, 30}
      Return numbers
   End Function

   Private Sub ShowNumbers(numbers As Integer())
      For index = 0 To numbers.GetUpperBound(0)
         Console.WriteLine($"{numbers(index)} ")
      Next
   End Sub
End Module
' The example displays the following output:
'   10
'   20
'   30
    

在下列範例中,GetNumbersMultiDim函式會傳回Integer(,),類型的二維陣列IntegerIn the following example, the GetNumbersMultiDim function returns an Integer(,), a two-dimensional array of type Integer. ShowNumbersMultiDim 程序接受 Integer(,) 引數。The ShowNumbersMultiDim procedure accepts an Integer(,) argument.


Module Example
   Public Sub Main()
      Dim numbers As Integer(,) = GetNumbersMultidim()
      ShowNumbersMultidim(numbers)
   End Sub

   Private Function GetNumbersMultidim() As Integer(,)
      Dim numbers As Integer(,) = {{1, 2}, {3, 4}, {5, 6}}
      Return numbers
   End Function

   Private Sub ShowNumbersMultidim(numbers As Integer(,))
      For index0 = 0 To numbers.GetUpperBound(0)
         For index1 = 0 To numbers.GetUpperBound(1)
            Console.Write($"{numbers(index0, index1)} ")
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'     1 2
'     3 4
'     5 6

不規則陣列Jagged arrays

有時候應用程式中的資料結構會是非矩形的二維陣列。Sometimes the data structure in your application is two-dimensional but not rectangular. 例如,您可能會使用陣列來儲存資料之每月每一天的高溫。For example, you might use an array to store data about the high temperature of each day of the month. 陣列的第一個維度來表示月份,但第二個維度代表天數,並在一個月的日數並不平均。The first dimension of the array represents the month, but the second dimension represents the number of days, and the number of days in a month is not uniform. A不規則的陣列,這也稱為陣列的陣列,專為這類案例。A jagged array, which is also called an array of arrays, is designed for such scenarios. 不規則的陣列是其項目也是陣列的陣列。A jagged array is an array whose elements are also arrays. 不規則陣列和不規則陣列中的每個項目都可以有一或多個維度。A jagged array and each element in a jagged array can have one or more dimensions.

下列範例會使用一個月份陣列,其中每個項目是陣列的天數。The following example uses an array of months, each element of which is an array of days. 由於不同月份的天數內的不同數字,此範例會使用不規則的陣列。The example uses a jagged array because different months have different numbers of days. 此範例示範如何建立不規則的陣列,將值指派給它,並擷取並顯示其值。The example shows how to create a jagged array, assign values to it, and retrieve and display its values.

Imports System.Globalization

Module JaggedArray
   Public Sub Main()
      ' Declare the jagged array of 12 elements. Each element is an array of Double.
      Dim sales(11)() As Double
      ' Set each element of the sales array to a Double array of the appropriate size.
      For month As Integer = 0 To 11
         ' The number of days in the month determines the appropriate size.
         Dim daysInMonth As Integer =
            DateTime.DaysInMonth(Year(Now), month + 1)
         sales(month) = New Double(daysInMonth - 1) {}
      Next 

      ' Store values in each element.
      For month As Integer = 0 To 11
         For dayOfMonth = 0 To sales(month).GetUpperBound(0)
            sales(month)(dayOfMonth) = (month * 100) + dayOfMonth
         Next
      Next

      ' Retrieve and display the array values.
      Dim monthNames = DateTimeFormatInfo.CurrentInfo.AbbreviatedMonthNames
      ' Display the month names.
      Console.Write("    ")
      For ctr = 0 To sales.GetUpperBound(0)
         Console.Write($" {monthNames(ctr)}   ")
      Next   
      Console.WriteLine()
      ' Display data for each day in each month.
      For dayInMonth = 0 To 30
         Console.Write($"{dayInMonth + 1,2}.  ")
         For monthNumber = 0 To sales.GetUpperBound(0)
            If dayInMonth > sales(monthNumber).GetUpperBound(0) Then 
               Console.Write("       ")
            Else
               Console.Write($"{sales(monthNumber)(dayInMonth),-5}  ")
            End If
         Next   
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'      Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
'  1.  0      100    200    300    400    500    600    700    800    900    1000   1100
'  2.  1      101    201    301    401    501    601    701    801    901    1001   1101
'  3.  2      102    202    302    402    502    602    702    802    902    1002   1102
'  4.  3      103    203    303    403    503    603    703    803    903    1003   1103
'  5.  4      104    204    304    404    504    604    704    804    904    1004   1104
'  6.  5      105    205    305    405    505    605    705    805    905    1005   1105
'  7.  6      106    206    306    406    506    606    706    806    906    1006   1106
'  8.  7      107    207    307    407    507    607    707    807    907    1007   1107
'  9.  8      108    208    308    408    508    608    708    808    908    1008   1108
' 10.  9      109    209    309    409    509    609    709    809    909    1009   1109
' 11.  10     110    210    310    410    510    610    710    810    910    1010   1110
' 12.  11     111    211    311    411    511    611    711    811    911    1011   1111
' 13.  12     112    212    312    412    512    612    712    812    912    1012   1112
' 14.  13     113    213    313    413    513    613    713    813    913    1013   1113
' 15.  14     114    214    314    414    514    614    714    814    914    1014   1114
' 16.  15     115    215    315    415    515    615    715    815    915    1015   1115
' 17.  16     116    216    316    416    516    616    716    816    916    1016   1116
' 18.  17     117    217    317    417    517    617    717    817    917    1017   1117
' 19.  18     118    218    318    418    518    618    718    818    918    1018   1118
' 20.  19     119    219    319    419    519    619    719    819    919    1019   1119
' 21.  20     120    220    320    420    520    620    720    820    920    1020   1120
' 22.  21     121    221    321    421    521    621    721    821    921    1021   1121
' 23.  22     122    222    322    422    522    622    722    822    922    1022   1122
' 24.  23     123    223    323    423    523    623    723    823    923    1023   1123
' 25.  24     124    224    324    424    524    624    724    824    924    1024   1124
' 26.  25     125    225    325    425    525    625    725    825    925    1025   1125
' 27.  26     126    226    326    426    526    626    726    826    926    1026   1126
' 28.  27     127    227    327    427    527    627    727    827    927    1027   1127
' 29.  28            228    328    428    528    628    728    828    928    1028   1128
' 30.  29            229    329    429    529    629    729    829    929    1029   1129
' 31.  30            230           430           630    730           930           1130

前一個範例會將值指派不規則陣列元素的元素為基礎來使用For...Next迴圈。The previous example assigns values to the jagged array on an element-by-element basis by using a For...Next loop. 您也可以使用巢狀的陣列常值,來指派的不規則陣列元素的值。You can also assign values to the elements of a jagged array by using nested array literals. 不過,嘗試使用巢狀陣列常值 (例如Dim valuesjagged = {{1, 2}, {2, 3, 4}}) 會產生編譯器錯誤BC30568However, the attempt to use nested array literals (for example, Dim valuesjagged = {{1, 2}, {2, 3, 4}}) generates compiler error BC30568. 若要更正錯誤,請先括號括住內部陣列常值的物件。To correct the error, enclose the inner array literals in parentheses. 括號會強制要評估陣列常值運算式,產生的值搭配外部陣列常值,如下列範例所示。The parentheses force the array literal expression to be evaluated, and the resulting values are used with the outer array literal, as the following example shows.


Module Example
   Public Sub Main()
      Dim values1d = { 1, 2, 3 }
      Dim values2d = {{1, 2}, {2, 3}, {3, 4}}
      Dim valuesjagged = {({1, 2}), ({2, 3, 4})}
   End Sub
End Module

不規則的陣列是一維陣列,其項目包含的陣列。A jagged array is a one-dimensional array whose elements contain arrays. 因此,Array.Length屬性和Array.GetLength(0)方法傳回一維陣列中的項目數並Array.GetLength(1)就會擲回IndexOutOfRangeException因為不規則的陣列不是多維度。Therefore, the Array.Length property and the Array.GetLength(0) method return the number of elements in the one-dimensional array, and Array.GetLength(1) throws an IndexOutOfRangeException because a jagged array is not multidimensional. 您擷取的每個子陣列的值來判斷每個子陣列中的項目數Array.Length屬性。You determine the number of elements in each subarray by retrieving the value of each subarray's Array.Length property. 下列範例說明如何判斷不規則陣列中的項目數。The following example illustrates how to determine the number of elements in a jagged array.


Module Example
   Public Sub Main()
      Dim jagged = { ({1, 2}), ({2, 3, 4}), ({5, 6}), ({7, 8, 9, 10}) }
      Console.WriteLine($"The value of jagged.Length: {jagged.Length}.")
      Dim total = jagged.Length
      For ctr As Integer = 0 To jagged.GetUpperBound(0)
         Console.WriteLine($"Element {ctr + 1} has {jagged(ctr).Length} elements.") 
         total += jagged(ctr).Length 
      Next
      Console.WriteLine($"The total number of elements in the jagged array: {total}")
   End Sub
End Module
' The example displays the following output:
'     The value of jagged.Length: 4.
'     Element 1 has 2 elements.
'     Element 2 has 3 elements.
'     Element 3 has 2 elements.
'     Element 4 has 4 elements.
'     The total number of elements in the jagged array: 15

長度為零的陣列Zero-length arrays

Visual Basic 會區別未初始化的陣列 (其值是的陣列Nothing) 和長度為零的陣列或空陣列 (陣列沒有任何項目。)未初始化的陣列是不被建立維度,或已指派給它的任何值。Visual Basic differentiates between a uninitialized array (an array whose value is Nothing) and a zero-length array or empty array (an array that has no elements.) An uninitialized array is one that has not been dimensioned or had any values assigned to it. 例如:For example:

Dim arr() As String

長度為零的陣列宣告具有-1 的維度。A zero-length array is declared with a dimension of -1. 例如:For example:

Dim arrZ(-1) As String

在下列情況中,您可能需要建立長度為零的陣列:You might need to create a zero-length array under the following circumstances:

  • 不必擔心NullReferenceException例外狀況,您的程式碼必須存取的成員Array類別,例如Length或是Rank,或呼叫 Visual Basic 函式,例如UBoundWithout risking a NullReferenceException exception, your code must access members of the Array class, such as Length or Rank, or call a Visual Basic function such as UBound.

  • 您想要保留您的程式碼的簡單,不需要檢查Nothing視為特殊案例。You want to keep your code simple by not having to check for Nothing as a special case.

  • 程式碼會與應用程式開發介面互動,這個介面會要求您傳遞長度為零的陣列給一個或多個程序,或從一個或多個程序傳回長度為零的陣列。Your code interacts with an application programming interface (API) that either requires you to pass a zero-length array to one or more procedures or returns a zero-length array from one or more procedures.

分割陣列Splitting an array

在某些情況下,您可能需要分成多個陣列中的單一陣列。In some cases, you may need to split a single array into multiple arrays. 這牽涉到的點或點陣列需要分割,是用來識別,然後吐陣列痰成兩個或多個不同的陣列。This involves identifying the point or points at which the array is to be split, and then spitting the array into two or more separate arrays.

注意

本節將不會討論將單一字串分割成字串陣列,根據某些分隔符號。This section does not discuss splitting a single string into a string array based on some delimiter. 如需將字串分割資訊,請參閱String.Split方法。For information on splitting a string, see the String.Split method.

最常用的準則來分割陣列如下:The most common criteria for splitting an array are:

  • 陣列中的項目數。The number of elements in the array. 例如,您可能要分成大約相等的部分數目超過指定的項目數的陣列。For example, you might want to split an array of more than a specified number of elements into a number of approximately equal parts. 基於此目的,您可以使用任一方法所傳回的值Array.LengthArray.GetLength方法。For this purpose, you can use the value returned by either the Array.Length or Array.GetLength method.

  • 做為分隔符號,指出應該將分割陣列項目的值。The value of an element, which serves as a delimiter that indicates where the array should be split. 您可以搜尋特定的值,藉由呼叫Array.FindIndexArray.FindLastIndex方法。You can search for a specific value by calling the Array.FindIndex and Array.FindLastIndex methods.

一旦您判定應處分割陣列的索引,您可以藉由呼叫,然後建立個別的陣列Array.Copy方法。Once you've determined the index or indexes at which the array should be split, you can then create the individual arrays by calling the Array.Copy method.

下列範例會將陣列分成兩個陣列的大小大約相同。The following example splits an array into two arrays of approximately equal size. (如果奇數的陣列項目總數,第一個陣列有一個元素,第二個)。(If the total number of array elements is odd, the first array has one more element than the second.)


Module Example
   Public Sub Main()
      ' Create an array of 100 elements.
      Dim arr(99) As Integer
      ' Populate the array.
      Dim rnd As new Random()
      For ctr = 0 To arr.GetUpperBound(0)
         arr(ctr) = rnd.Next()
      Next
      
      ' Determine how many elements should be in each array.
      Dim divisor = 2
      Dim remainder As Integer
      Dim boundary = Math.DivRem(arr.GetLength(0), divisor, remainder)
            
      ' Copy the array.
      Dim arr1(boundary - 1 + remainder), arr2(boundary - 1) as Integer
      Array.Copy(arr, 0, arr1, 0, boundary + remainder)
      Array.Copy(arr, boundary + remainder, arr2, 0, arr.Length - boundary) 
   End Sub
End Module

下列範例會將字串陣列分成兩個陣列,根據其值為"zzz",以做為陣列分隔符號的項目出現與否。The following example splits a string array into two arrays based on the presence of an element whose value is "zzz", which serves as the array delimiter. 新的陣列不包含包含分隔符號的項目。The new arrays do not include the element that contains the delimiter.


Module Example
   Public Sub Main()
      Dim rnd As New Random()
      
      ' Create an array of 100 elements.
      Dim arr(99) As String
      ' Populate each element with an arbitrary ASCII character.
      For ctr = 0 To arr.GetUpperBound(0)
         arr(ctr) = ChrW(Rnd.Next(&h21, &h7F))
      Next
      ' Get a random number that will represent the point to insert the delimiter.
      arr(rnd.Next(0, arr.GetUpperBound(0))) = "zzz"

      ' Find the delimiter.
      Dim location = Array.FindIndex(arr, Function(x) x = "zzz")

      ' Create the arrays.
      Dim arr1(location - 1) As String
      Dim arr2(arr.GetUpperBound(0) - location - 1) As String
      
      ' Populate the two arrays.
      Array.Copy(arr, 0, arr1, 0, location)
      Array.Copy(arr, location + 1, arr2, 0, arr.GetUpperBound(0) - location)
   End Sub
End Module

加入陣列Joining arrays

您也可以結合數目的陣列合併為單一較大的陣列。You can also combine a number of arrays into a single larger array. 若要這樣做,您也使用Array.Copy方法。To do this, you also use the Array.Copy method.

注意

本節將不會討論聯結成單一字串的字串陣列。This section does not discuss joining a string array into a single string. 如需有關聯結的字串陣列,請參閱String.Join方法。For information on joining a string array, see the String.Join method.

之前每個陣列項目複製到新的陣列,您必須先確定,您就已初始化陣列,使它足夠大以容納新的陣列。Before copying the elements of each array into the new array, you must first ensure that you have initialized the array so that it is large enough to accommodate the new array. 您可以使用下列其中一種做法:You can do this in one of two ways:

  • 使用 ReDim Preserve 陳述式,以動態方式加入新項目之前展開的陣列。Use the ReDim Preserve statement to dynamically expand the array before adding new elements to it. 這是最簡單的技巧,但它可能會導致效能降低,過多的記憶體耗用量當您複製大型陣列。This is the easiest technique, but it can result in performance degradation and excessive memory consumption when you are copying large arrays.
  • 計算新的大型陣列所需的項目總數,然後將每個來源陣列的項目加入至它。Calculate the total number of elements needed for the new large array, then add the elements of each source array to it.

下列範例會使用第二種方法,將四個的陣列,具有十個項目新增至單一的陣列。The following example uses the second approach to add four arrays with ten elements each to a single array.

Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer()))
      ' Generate four arrays.
      For ctr = 0 To 3
         Dim value = ctr
         tasks.Add(Task.Run(Function()
                               Dim arr(9) As Integer
                               For ndx = 0 To arr.GetUpperBound(0)
                                  arr(ndx) = value
                               Next
                               Return arr
                            End Function))   
       Next
       Task.WaitAll(tasks.ToArray())
       ' Compute the number of elements in all arrays.
       Dim elements = 0
       For Each task In tasks
          elements += task.Result.Length
       Next
       Dim newArray(elements - 1) As Integer
       Dim index = 0
       For Each task In tasks
          Dim n = task.Result.Length
          Array.Copy(task.Result, 0, newArray, index, n)
          index += n
       Next 
      Console.WriteLine($"The new array has {newArray.Length} elements.")
   End Sub
End Module
' The example displays the following output:
'     The new array has 40 elements.

在此情況下,來源陣列是所有小型的因為我們也會動態地可以展開陣列,因為我們將新增它的每個新的陣列項目。Since in this case the source arrays are all small, we can also dynamically expand the array as we add the elements of each new array to it. 下列範例正是如此。The following example does that.

Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer()))
      ' Generate four arrays.
      For ctr = 0 To 3
         Dim value = ctr
         tasks.Add(Task.Run(Function()
                               Dim arr(9) As Integer
                               For ndx = 0 To arr.GetUpperBound(0)
                                  arr(ndx) = value
                               Next
                               Return arr
                            End Function))   
       Next
       Task.WaitAll(tasks.ToArray())

       ' Dimension the target array and copy each element of each source array to it.
       Dim newArray() As Integer = {}
       ' Define the next position to copy to in newArray.
       Dim index = 0
       For Each task In tasks
          Dim n = Task.Result.Length
          ReDim Preserve newArray(newArray.GetUpperBound(0) + n)
          Array.Copy(task.Result, 0, newArray, index, n)
          index += n
       Next 
      Console.WriteLine($"The new array has {newArray.Length} elements.")
   End Sub
End Module
' The example displays the following output:
'     The new array has 40 elements.

使用集合取代陣列Collections as an alternative to arrays

陣列是最適用於建立和處理固定數目的強類型物件。Arrays are most useful for creating and working with a fixed number of strongly typed objects. 集合會提供較具彈性的方式來使用物件群組。Collections provide a more flexible way to work with groups of objects. 不同於陣列,而這需要您明確變更陣列的大小ReDim陳述式,集合動態增長或縮減為應用程式變更的需要。Unlike arrays, which require that you explicitly change the size of an array with the ReDim Statement, collections grow and shrink dynamically as the needs of an application change.

當您使用ReDim重訂維度陣列,Visual Basic 建立新的陣列和釋放前一個。When you use ReDim to redimension an array, Visual Basic creates a new array and releases the previous one. 這將佔用執行時間。This takes execution time. 因此,如果您正在使用經常變更,或您的項目數目無法預測您需要的項目數目上限,您會使用集合通常取得較佳的效能。Therefore, if the number of items you are working with changes frequently, or you cannot predict the maximum number of items you need, you'll usually obtain better performance by using a collection.

對於某些集合,您可以將鍵值指派給您放入集合的任何物件,讓您可以藉由使用鍵值快速擷取物件。For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

如果集合包含只有一個資料類型的項目,則可使用 System.Collections.Generic 命名空間內的其中一個類別。If your collection contains elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. 泛型集合會強制類型安全,如此就不會加入其他資料類型。A generic collection enforces type safety so that no other data type can be added to it.

如需集合的詳細資訊,請參閱集合For more information about collections, see Collections.

詞彙Term 定義Definition
Array Dimensions in Visual BasicArray Dimensions in Visual Basic 說明陣列中的順位和維度。Explains rank and dimensions in arrays.
如何:初始化陣列變數在 Visual BasicHow to: Initialize an Array Variable in Visual Basic 描述如何在陣列中填入初始值。Describes how to populate arrays with initial values.
如何:在 Visual Basic 中排序陣列How to: Sort An Array in Visual Basic 示範如何依字母順序排列陣列中的項目。Shows how to sort the elements of an array alphabetically.
如何:指派一個陣列至另一個陣列How to: Assign One Array to Another Array 描述將陣列指派給另一個陣列變數的規則和步驟。Describes the rules and steps for assigning an array to another array variable.
陣列的疑難排解Troubleshooting Arrays 討論在使用陣列時會引發的一些常見問題。Discusses some common problems that arise when working with arrays.

另請參閱See also