通过在子句中包含 New 数组文本并指定数组的初始值来初始化数组变量。 可以指定类型,也可以允许从数组字面量中的值推断。 有关如何推断类型的详细信息,请参阅数组中的“使用初始值填充 数组”。
使用数组字面量初始化数组变量
在子句 New 中,或者在分配数组值时,请在大括号({})内提供元素的值。 以下示例演示了多种声明、创建和初始化变量的方法,以包含类型 Char为元素的数组。
' The following five lines of code create the same array.
' Preferred syntaxes are on the lines with chars1 and chars2.
Dim chars1 = {"%"c, "&"c, "@"c}
Dim chars2 As Char() = {"%"c, "&"c, "@"c}
Dim chars3() As Char = {"%"c, "&"c, "@"c}
Dim chars4 As Char() = New Char(2) {"%"c, "&"c, "@"c}
Dim chars5() As Char = New Char(2) {"%"c, "&"c, "@"c}
执行每个语句后,创建的数组的长度为 3,索引为 0 到索引 2 的元素包含初始值。 如果同时提供上限和值,则必须为索引0到达上限的每个元素提供一个值。
请注意,如果在数组字面量中提供元素值,则无需指定索引上限。 如果未指定上限,则根据数组文本中的值数推断数组的大小。
使用数组文本初始化多维数组变量
将值嵌套在大括号 ({}) 内。 确保嵌套的数组字面量都推断为相同类型和长度的数组。 下面的代码示例演示了多维数组初始化的几个示例。
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
Dim customerData = {{"City Power & Light", "http://www.cpandl.com/"},
{"Wide World Importers", "http://wideworldimporters.com"},
{"Lucerne Publishing", "http://www.lucernepublishing.com"}}
' You can nest array literals to create arrays that have more than two
' dimensions.
Dim twoSidedCube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
可以显式指定数组边界,或者将其排除,让编译器根据数组文本中的值推断数组边界。 如果同时提供上限和值,则必须在每个维度中包括索引 0 到上限的每个元素的值。 以下示例展示了几种声明、创建和初始化变量的方法,以包含元素类型为Short的二维数组。
' The following five lines of code create the same array.
' Preferred syntaxes are on the lines with scores1 and scores2.
Dim scores1 = {{10S, 10S, 10S}, {10S, 10S, 10S}}
Dim scores2 As Short(,) = {{10, 10, 10}, {10, 10, 10}}
Dim scores3(,) As Short = {{10, 10, 10}, {10, 10, 10}}
Dim scores4 As Short(,) = New Short(1, 2) {{10, 10, 10}, {10, 10, 10}}
Dim scores5(,) As Short = New Short(1, 2) {{10, 10, 10}, {10, 10, 10}}
执行每个语句后,创建的数组包含六个具有索引 (0,0)、 (0,1)、 (0,2)、 (1,0)、 (1,1)和的 (1,2)初始化元素。 每个数组位置都包含值 10。
下面的示例循环访问多维数组。 在用 Visual Basic 编写的 Windows 控制台应用程序中,将代码粘贴到方法中 Sub Main() 。 最后一个注释显示输出。
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
' Iterate through the array.
For index0 = 0 To numbers.GetUpperBound(0)
For index1 = 0 To numbers.GetUpperBound(1)
Debug.Write(numbers(index0, index1).ToString & " ")
Next
Debug.WriteLine("")
Next
' Output
' 1 2
' 3 4
' 5 6
使用数组字面量初始化交错数组变量
将对象值嵌套在大括号内 ({}) 。 尽管还可以嵌套指定不同长度数组的数组字面量,但是对于交错数组,请确保嵌套的数组字面量括在括号 (()) 中。 括号强制对嵌套数组字面量进行计算,生成的数组被用作锯齿状数组的初始值。 下面的代码示例演示了两个交错数组初始化示例。
' Create a jagged array of arrays that have different lengths.
Dim jaggedNumbers = {({1, 2, 3}), ({4, 5}), ({6}), ({7})}
' Create a jagged array of Byte arrays.
Dim images = {New Byte() {}, New Byte() {}, New Byte() {}}
下面的示例循环访问交错数组。 在用 Visual Basic 编写的 Windows 控制台应用程序中,将代码粘贴到方法中 Sub Main() 。 代码中的最后一个注释显示输出。
' Create a jagged array of arrays that have different lengths.
Dim jaggedNumbers = {({1, 2, 3}), ({4, 5}), ({6}), ({7})}
For indexA = 0 To jaggedNumbers.Length - 1
For indexB = 0 To jaggedNumbers(indexA).Length - 1
Debug.Write(jaggedNumbers(indexA)(indexB) & " ")
Next
Debug.WriteLine("")
Next
' Output:
' 1 2 3
' 4 5
' 6
' 7
另请参阅
数组
数组疑难解答