集合初始化程式

  • 陣列

     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"
     }