首页
学习
活动
专区
工具
TVP
发布

VB.Net - 数组

数组存储相同类型的元素的固定大小顺序集合。 数组用于存储数据集合,但将数组视为同一类型的变量的集合通常更有用。

所有数组由连续的内存位置组成。 最低地址对应于第一个元素,最高地址对应于最后一个元素。

在VB.Net中创建数组

要在VB.Net中声明数组,可以使用Dim语句。 例如,

Dim intData(30)	  ' an array of 31 elements
Dim strData(20) As String	' an array of 21 strings
Dim twoDarray(10, 20) As Integer	'a two dimensional array of integers
Dim ranges(10, 100)	 'a two dimensional array

您还可以在声明数组时初始化数组元素。 例如,

Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}

可以通过使用数组的索引来存储和访问数组中的元素。 以下程序演示了这一点:

Module arrayApl
   Sub Main()
      Dim n(10) As Integer  ' n is an array of 11 integers '
      Dim i, j As Integer
      ' initialize elements of array n '         
      For i = 0 To 10
          n(i) = i + 100 ' set element at location i to i + 100 
      Next i
      ' output each array element's value '
      For j = 0 To 10
          Console.WriteLine("Element({0}) = {1}", j, n(j))
      Next j
      Console.ReadKey()
   End Sub
End Module

当上述代码被编译和执行时,它产生了以下结果:

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

动态数组

动态数组是可以根据程序需要进行维度和重新定义的数组。 您可以使用ReDim语句声明一个动态数组。