如何:创建集合初始值设定项所使用的集合 (Visual Basic)

使用集合初始值设定项创建集合时,Visual Basic 编译器会搜索该集合类型的 Add 方法,所搜索的 Add 方法的参数要与用于该集合的集合初始值设定项中的值类型相匹配。此 Add 方法用于以集合初始值设定项中的值填充集合。

示例

下面的示例演示 OrderCollection 集合,该集合包含一个公共 Add 方法,集合初始值设定项可使用该方法添加 Order 类型的对象。Add 方法允许使用集合初始值设定项的缩写语法。

Public Class Customer
    Public Property Id As Integer
    Public Property Name As String
    Public Property Orders As OrderCollection

    Public Sub New(ByVal id As Integer, ByVal name As String, ByVal orders As OrderCollection)
        Me.Id = id
        Me.Name = name
        Me.Orders = orders
    End Sub
End Class

Public Class Order
    Public Property Id As Integer
    Public Property CustomerId As Integer
    Public Property OrderDate As DateTime

    Public Sub New(ByVal id As Integer,
                   ByVal customerId As Integer,
                   ByVal orderDate As DateTime)
        Me.Id = id
        Me.CustomerId = customerId
        Me.OrderDate = orderDate
    End Sub
End Class
Public Class OrderCollection
    Implements IEnumerable(Of Order)

    Dim items As New List(Of Order)

    Public Property Item(ByVal index As Integer) As Order
        Get
            Return CType(Me(index), Order)
        End Get
        Set(ByVal value As Order)
            items(index) = value
        End Set
    End Property

    Public Sub Add(ByVal id As Integer, ByVal customerID As Integer, ByVal orderDate As DateTime)
        items.Add(New Order(id, customerID, orderDate))
    End Sub

    Public Function GetEnumerator() As IEnumerator(Of Order) Implements IEnumerable(Of Order).GetEnumerator
        Return items.GetEnumerator()
    End Function

    Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Me.GetEnumerator()
    End Function
End Class
Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Sub Add(ByVal genericList As List(Of Customer),
            ByVal id As Integer,
            ByVal name As String,
            ByVal orders As OrderCollection)

        genericList.Add(New Customer(id, name, orders))
    End Sub
End Module
Dim customerList = New List(Of Customer) From
  {
    {1, "John Rodman", New OrderCollection From {{9, 1, #6/12/2008#},
                                                 {8, 1, #6/11/2008#},
                                                 {5, 1, #5/1/2008#}}},
    {2, "Ariane Berthier", New OrderCollection From {{2, 2, #1/18/2008#},
                                                     {4, 2, #3/8/2008#},
                                                     {6, 2, #3/18/2008#},
                                                     {7, 2, #5/14/2008#},
                                                     {5, 2, #4/4/2008#}}},
     {3, "Brian Perry", New OrderCollection From {{1, 3, #1/15/2008#},
                                                  {3, 3, #3/8/2008#}}}
  }

请参见

任务

如何:创建集合初始值设定项所使用的 Add 扩展方法 (Visual Basic)

概念

集合初始值设定项 (Visual Basic)