萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 實作 ArrayList 類別:動態陣列 Add/Count/Item

使用範例

<%
Dim arr : Set arr = New ArrayList
arr.Add "a" : arr.Add "b" : arr.Add "c"
Response.Write arr.Count & "
" ' 3 For i = 0 To arr.Count - 1 Response.Write arr.Item(i) & "
" Next Set arr = Nothing %>

類別實作

Class ArrayList
    Private m_array()
    Private m_count
    
    Private Sub Class_Initialize()
        ReDim m_array(0)
        m_count = 0
    End Sub
    
    Private Sub Class_Terminate()
        ReDim m_array(0)
        m_count = 0
    End Sub
    
    Public Property Get Count()
        Count = m_count
    End Property
    
    Public Property Get Item(index)
        Item = m_array(index)
    End Property
    
    Public Function Add(arrItem)
        ReDim Preserve m_array(m_count)
        m_array(m_count) = arrItem
        m_count = m_count + 1
    End Function
End Class

特性與限制

  • 模擬 .NET ArrayList 基本功能:動態擴充、索引存取、計數。
  • 效能:每次 Add 都 ReDim Preserve 會複製陣列,大量資料建議預先配置容量或改用 Scripting.Dictionary。
  • 型別:Variant 陣列可存放任意型別(物件、陣列、字串)。
  • 缺少功能:Insert、RemoveAt、Clear、IndexOf、ToArray 等。

擴充範例:RemoveAt

Public Function RemoveAt(index)
    If index < 0 Or index >= m_count Then Exit Function
    Dim i
    For i = index To m_count - 2
        m_array(i) = m_array(i + 1)
    Next
    ReDim Preserve m_array(m_count - 1)
    m_count = m_count - 1
End Function
copyright © 萬盛學電腦網 all rights reserved