集合初始化程序

  • 数组

     Dim names = {"Foo", "Bar"} ' Inferred as String()
     Dim numbers = {1, 5, 42} ' Inferred as Integer()
    
  • 容器(List(Of T)Dictionary(Of TKey, TValue) 等)

     Dim names As New List(Of String) From {
         "Foo",
         "Bar"
         '...
     }
    
     Dim indexedDays As New Dictionary(Of Integer, String) From {
         {0, "Sun"},
         {1, "Mon"}
         '...
     }
    

    相当于

     Dim indexedDays As New Dictionary(Of Integer, String)
     indexedDays.Add(0, "Sun")
     indexedDays.Add(1, "Mon")
     '...
    

    项可以是构造函数,方法调用,属性访问的结果。它也可以与 Object 初始化程序混合使用。

     Dim someList As New List(Of SomeClass) From {
         New SomeClass(argument),
         New SomeClass With { .Member = value },
         otherClass.PropertyReturningSomeClass,
         FunctionReturningSomeClass(arguments)
         '...
     }
    

    不可能同时对同一对象使用 Object 初始化程序语法集合初始化程序语法。例如,这些将无法正常工作

     Dim numbers As New List(Of Integer) With {.Capacity = 10} _
                                         From { 1, 5, 42 }
    
     Dim numbers As New List(Of Integer) From {
         .Capacity = 10,
         1, 5, 42
     }
    
     Dim numbers As New List(Of Integer) With {
         .Capacity = 10,
         1, 5, 42
     }
    
  • 自定义类型

    我们还可以通过提供自定义类型来允许集合初始化程序语法。
    它必须实现 IEnumerable 并且具有可访问和兼容的过载规则 Add 方法(实例,共享或甚至扩展方法)

    举例:

     Class Person
         Implements IEnumerable(Of Person) ' Inherits from IEnumerable
    
         Private ReadOnly relationships As List(Of Person)
    
         Public Sub New(name As String)
             relationships = New List(Of Person)
         End Sub
    
         Public Sub Add(relationName As String)
             relationships.Add(New Person(relationName))
         End Sub
    
         Public Iterator Function GetEnumerator() As IEnumerator(Of Person) _
             Implements IEnumerable(Of Person).GetEnumerator
    
             For Each relation In relationships
                 Yield relation
             Next
         End Function
    
         Private Function IEnumerable_GetEnumerator() As IEnumerator _ 
             Implements IEnumerable.GetEnumerator
    
             Return GetEnumerator()
         End Function
     End Class
    
     ' Usage
     Dim somePerson As New Person("name") From {
         "FriendName",
         "CoWorkerName"
         '...
     }
    

    如果我们想通过将名称放在集合初始值设定项中来将 Person 对象添加到 List(Of Person)(但是我们不能修改 List(Of Person)类)我们可以使用 Extension 方法

     ' Inside a Module
     <Runtime.CompilerServices.Extension>
     Sub Add(target As List(Of Person), name As String)
         target.Add(New Person(name))
     End Sub
    
     ' Usage
     Dim people As New List(Of Person) From {
         "Name1", ' no need to create Person object here
         "Name2"
     }