LotusScript中的可变长度的数组在用来存放不确定数量的值时很有用,可以类比于C#和Java里的Collection。但在不断添加内容时,需要重复使用Redim Preserve语句,不甚方便。我们可以编写一个简单的自定义类,实现同样的功能,又具有友好的调用方法。
%REM Class NArray Comments for Class %END REM Public Class NArray private container() As Variant Private pointer As Integer 'points to the next empty position Sub New() End Sub %REM The number of elements %END REM Public Property Get Count As Integer Count=pointer End Property Function ToArray As Variant If pointer=0 Then Exit Function End If Dim result() As Variant ReDim result(pointer-1) Dim i As Integer For i=0 To pointer-1 result(i)=container(i) Next ToArray=result End Function Public Function Add(elem As Variant) 'dynamic bound ReDim preserve container(pointer) Call SetValue(container(pointer), elem) pointer=pointer+1 End Function Function Item(index As Integer) Call SetValue(Item, container(index)) End Function Function Contains(elem As Variant) As Boolean ForAll v In Container If Equals(v, elem) Then Contains=True Exit Function End If End ForAll Contains=False End Function Public Function Import(concat As String, delimiter As String) If delimiter="" Then delimiter=", " End If Dim v v=Split(concat, delimiter) ForAll s In v me.Add(s) End ForAll End Function Function AddArray(array As Variant) ForAll e In array Add(e) End ForAll End Function Function Clear() ReDim container(0) pointer=0 End Function 'The container property is a Variant array and cannot be assigned to variables. Public Function ToStringArray() As Variant If pointer=0 Then Exit Function End If Dim v() As String ReDim v(pointer-1) Dim i As Integer For i=0 To pointer-1 v(i)=CStr(container(i)) Next ToStringArray=v End Function Public Function ToDoubleArray() As Variant If pointer=0 Then Exit Function End If Dim v() As Double ReDim v(pointer-1) Dim i As Integer For i=0 To pointer-1 v(i)=CDbl(container(i)) Next ToDoubleArray=v End Function Public Function ToDateArray() As Variant If pointer=0 Then Exit Function End If Dim v() As Variant ReDim v(pointer-1) Dim i As Integer For i=0 To pointer-1 v(i)=CDat(container(i)) Next ToDateArray=v End Function Function Map(ctype As String) As Variant Dim copy As Variant copy=ToArray Map=ArrayMap(copy, ctype) End Function Function FullTrim() Dim i As Integer For i=0 To pointer-1 If DataType(container(i))=V_STRING Then container(i)=Trim(container(i)) End If Next End Function End Class
在新建一个NArray对象后就可以通过调用Add方法添加值。Import方法是为了简化添加多个字符串,类似于字符串的Split函数。实际存放值的可变长度数组Container也是一个公共字段,必要时可以直接访问。
如果需要,还可以为NArray添加其它一些功能,比如向构造函数传入一个数组,或是增加一个方法可以接受数组作为参数,之后将这个数组中的元素添加到NArray里。