VB.NET - 整数数组需要实例化,如何?

Day*_*yan 3 vb.net

第一次尝试

Dim holdValues() As Integer 'Doesn't Work
holdValues(1) = 55
Run Code Online (Sandbox Code Playgroud)

第二次尝试

Dim holdValues(-1) As Integer 'Gives me Index was outside the bounds of the array.
holdValues(1) = 55
Run Code Online (Sandbox Code Playgroud)

我正在尝试做类似的事情

 Dim myString(-1) As String
Run Code Online (Sandbox Code Playgroud)

但显然这不适用于整数数组.我不知道阵列的大小是多少,它不会变小但会变大.

任何帮助将不胜感激,谢谢!

Mic*_*ues 11

您可以使用Initializers快捷方式:

Dim myValues As Integer() = New Integer() {55, 56, 67}
Run Code Online (Sandbox Code Playgroud)

但是如果你想调整数组的大小等等,那么肯定看一下List(Of Integer):

'Initialise the list
Dim myValues As New System.Collections.Generic.List(Of Integer)

'Shortcut to pre-populate it with known values
myValues.AddRange(New Integer() {55, 56, 57})

'Add a new value, dynamically resizing the array
myValues.Add(32)

'It probably has a method do do what you want, but if you really need an array:
myValues.ToArray()
Run Code Online (Sandbox Code Playgroud)


Eri*_*son 10

你添加号码

holdValues(x) //x+1 will be size of array
Run Code Online (Sandbox Code Playgroud)

所以这样的事情

Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
Run Code Online (Sandbox Code Playgroud)

如果需要,你可以通过这样做重新分配数组.

ReDim array(10) as Integer 
Run Code Online (Sandbox Code Playgroud)

当你应该让你的阵列更大时,你将不得不添加你的代码.您还可以查看列表.列表会自动处理此问题.

这里有一些关于列表的信息:http://www.dotnetperls.com/list-vbnet

希望这可以帮助.

也是关于数组的一般知识的链接http://www.dotnetperls.com/array-vbnet