非零下限
使用 Option Strict On
,雖然 .NET Framework 允許建立具有非零下限的單維陣列,但它們不是向量,因此與 VB.NET 型別陣列不相容。這意味著它們只能被視為 Array
,因此不能使用普通陣列 (index)
引用。
Dim a As Array = Array.CreateInstance(GetType(Integer), {4}, {-1})
For y = LBound(a) To UBound(a)
a.SetValue(y * y, y)
Next
For y = LBound(a) To UBound(a)
Console.WriteLine($"{y}: {a.GetValue(y)}")
Next
除了使用 Option Strict Off
,你可以通過將陣列視為 IList
來獲得 (index)
語法,但是它不是陣列,所以你不能在變數名上使用 LBound
和 UBound
(你仍然沒有避免拳擊):
Dim nsz As IList = a
For y = LBound(a) To UBound(a)
nsz(y) = 2 - CInt(nsz(y))
Next
For y = LBound(a) To UBound(a)
Console.WriteLine($"{y}: {nsz(y)}")
Next
多維非零下界陣列是相容 VB.NET 多維型別化的陣列:
Dim nza(,) As Integer = DirectCast(Array.CreateInstance(GetType(Integer),
{4, 3}, {1, -1}), Integer(,))
For y = LBound(nza) To UBound(nza)
For w = LBound(nza, 2) To UBound(nza, 2)
nza(y, w) = -y * w + nza(UBound(nza) - y + LBound(nza),
UBound(nza, 2) - w + LBound(nza, 2))
Next
Next
For y = LBound(nza) To UBound(nza)
Dim ly = y
Console.WriteLine(String.Join(" ",
Enumerable.Repeat(ly & ":", 1).Concat(
Enumerable.Range(LBound(nza, 2), UBound(nza, 2) - LBound(nza, 2) + 1) _
.Select(Function(w) CStr(nza(ly, w))))))
Next
MSDN 參考: Array.CreateInstance