次の方法で共有


Workaround: Arrays with non-zero lower bounds

Posted by: Phil Weber, VB MVP
This post applies to Visual Basic .NET 2002/2003/2005

OK, now that Paul Vick has explained why VB.NET doesn't support arrays with non-zero lower bounds, let's see how we can do them anyway. ;-)

Say you want to store a collection of annual values in an array of integers. It's reasonable that the array index would correspond to the year in question; that is, TotalSales(1981) would contain the sales total for the year 1981.

In pre-.NET versions of VB, we could simply do this:

     Dim TotalSales(1981 To 2000) As Integer

Problem solved. But as Paul has explained, VB.NET no longer lets us do that. We can, however, do this:

     Dim TotalSales As New VBArray(1981, 2000)
    TotalSales(1981) = 345
    TotalSales(2000) = 995
    Console.WriteLine(TotalSales(1981))
    Console.WriteLine(TotalSales(2000))

I can live with that, how about you?

This class (based on this post by Eric Gunnerson) is what makes it all possible:

 Public Class VBArray
     Private _lbound As Integer
     Private _int() As Integer 

     Public Sub New(ByVal LBound As Integer, ByVal UBound As Integer)
         Me.ReDim(LBound, UBound)
     End Sub 

     Public Sub [ReDim](ByVal LBound As Integer, ByVal UBound As Integer)
         _lbound = LBound
         ReDim _int(UBound - LBound + 1)
     End Sub 

     Default Public Property Item(ByVal Index As Integer) As Integer
         Get
             Return _int(Index - _lbound)
         End Get
         Set(ByVal Value As Integer)
             _int(Index - _lbound) = Value
         End Set
     End Property 

     Public Function ToArray() As Integer()
         Return _int
     End Function
 End Class

I've included a ToArray method which returns the underlying array, in case you need to pass it to another method, or manipulate it in other array-type ways.

Note that this class is hard-coded to handle Integers; in VB.NET 2002/2003, you must create a separate class for each array type you wish to simulate. Generics in Visual Basic .NET 2005 will make this sort of thing much cleaner.

Comments