非零下限
使用 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