Collection.Add(Object, String, Object, Object) 方法

定义

将元素添加到 Collection 对象。

public void Add(object? Item, string? Key = default, object? Before = default, object? After = default);
public void Add(object Item, string Key = default, object Before = default, object After = default);
member this.Add : obj * string * obj * obj -> unit
Public Sub Add (Item As Object, Optional Key As String = Nothing, Optional Before As Object = Nothing, Optional After As Object = Nothing)

参数

Item
Object

必填。 指定要添加到集合中的元素的任何类型的对象。

Key
String

Optional. 一个唯 String 一表达式,指定一个键字符串,该字符串可用于访问集合中的此新元素,而不是位置索引。

Before
Object

Optional. 指定集合中的相对位置的表达式。 要添加的元素放置在集合中,然后放置自变量标识的 Before 元素。 如果 Before 为数值表达式,则它必须是从 1 到集合属性的值中的 Count 数字。 如果 BeforeString 表达式,则它必须与在将引用的元素添加到集合时指定的键字符串相对应。 不能同时指定 BeforeAfter

After
Object

Optional. 指定集合中的相对位置的表达式。 要添加的元素放置在由参数标识的元素之后的集合中 After 。 如果 After 为数值表达式,则它必须是从 1 到集合属性的值中的 Count 数字。 如果 AfterString 表达式,则它必须与在将引用的元素添加到集合时指定的键字符串相对应。 不能同时指定 BeforeAfter

示例

下面的示例使用Add该方法将名为child包含child属性Public的类的实例的对象添加到name调用family的集合中。 若要查看其工作原理,请创建一个包含两个Form控件的控件,并将其Button属性Text设置为和 AddListchild 类定义和 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() 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() Handles Button2.Click
    For Each aChild As child In family
        MsgBox(aChild.name)
    Next
End Sub

注解

BeforeAfter参数必须引用集合的现有元素;否则会发生错误。

如果省略了参数 BeforeAfter 参数,则将新对象添加到集合的末尾。

如果指定的 Key 值与集合的现有元素的键匹配,也会出现错误。

适用于