这是一个简单的问题 - 如何在 VB.NET 中创建一个索引从 1 开始的对象数组?
我需要这样一个对象来将范围写回 Excel 电子表格,并且它仅接受基于 1 的索引。
当我从 Excel 读取范围时,它会自动在 VB.NET 中创建一个基于 1 的对象,但是当我尝试创建另一个对象时,它不允许我将 lBound 设置为 1。
您可以使用
Array.CreateInstance
来实现您想要的。
' create an array of 10 items with lower bound index of 1
Dim arrayStartingWith1 As Array = Array.CreateInstance(GetType(Integer), New Integer(0) {10}, New Integer(0) {1})
' this is now incorrect
' arrayStartingWith1(0) = 1
' this is correct
arrayStartingWith1(1) = 1
arrayStartingWith1(10) = 1
这是一个二维数组,否则与 Szymon 的答案类似。
Public Shared Function GetBlankRangeArray(RowCount As Integer, ColumnCount As Integer) As Object(,)
Dim arrayStartingWith1 As Array =
Array.CreateInstance(GetType(Object),
New Integer(1) {RowCount, ColumnCount},
New Integer(1) {1, 1})
Return arrayStartingWith1
End Function