Share via


Add 方法 (集合物件)

更新:2007 年 11 月

將項目加入至 Collection 物件。

Public Sub Add( _
   ByVal Item As Object, _
   Optional ByVal Key As String, _
   Optional ByVal { Before | After } As Object = Nothing _
)

參數

  • Item
    必要項。任何型別的物件,用來指定要加入至集合的項目。

  • Key
    選擇項,唯一的 String 運算式,指定用來存取集合中這個新項目的索引鍵字串,藉以取代位置索引。

  • Before
    選擇項,指定集合物件中相關位置的運算式。要加入的項目會放置在集合中由 Before 引數識別的項目之前。如果 Before 是數值運算式,則必須介於 1 與集合的 Count 屬性 (Collection 物件) 值之間。如果 Before 是 String 運算式,則它必須與在參考項目加入至集合時指定的索引鍵字串對應。您無法同時指定 Before 和 After。

  • After
    選擇項,指定集合物件中相關位置的運算式。要加入的項目會放置在集合中由 After 引數識別的項目之後。如果 After 是數值運算式,則必須介於 1 與集合的 Count 屬性值之間。如果 After 是 String 運算式,則它必須與在參考項目加入至集合時指定的索引鍵字串對應。您無法同時指定 Before 和 After。

例外狀況/錯誤代碼

例外狀況類型

錯誤代碼

條件

ArgumentException

5

  • 同時指定了 Before 和 After。

  • Before 或 After 引數不是參考集合的現有項目。

  • 指定的 Key 已存在。

如果將使用非結構化錯誤處理的 Visual Basic 6.0 應用程式升級,請參閱「錯誤代碼」資料行 (您可以將錯誤代碼與 Number 屬性 (Err 物件) 比對)。但是,請盡可能考慮以 Visual Basic 的結構化例外處理概觀 取代這類錯誤控制項。

備註

Before 或 After 引數必須參考集合中的現有項目,否則將會發生錯誤。

如果指定的 Key 值與集合現有項目的索引鍵相符,則也會發生錯誤。

範例

下列範例使用 Add 方法,將 child 物件 (child 類別的執行個體,其包含 Public 屬性 name) 加入至 family 集合中。若要了解其運作方式,請建立具有兩個 Button 控制項的 Form,並將它們的 Text 屬性設定為 Add 和 List。將 child 類別定義和 family 宣告加入表單程式碼中。為 [加入] 和 [清單] 按鈕修改 _Click 事件處理常式,如下所示。[加入] 按鈕可讓您加入子系,而 [清單] 按鈕則會顯示所有子系的名稱。

Public Class child
    Public name As String
    Sub New(ByVal newName As String)
        name = newName
    End Sub
End Class
' Create a Collection object.
Private family As New Collection()
Private Sub addChild_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    Dim newName As String
    newName = InputBox("Name of new family member: ")
    If newName <> "" Then
        family.Add(New child(newName), newName)
    End If
End Sub
Private Sub listChild_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button2.Click
    For Each aChild As child In family
        MsgBox(aChild.name)
    Next
End Sub

需求

命名空間 (Namespace)︰Microsoft.VisualBasic

**模組︰**Collection

組件:Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

Collection 物件 (Visual Basic)

Item 屬性 (Collection 物件)

Remove 方法 (Collection 物件)