[VB.NET]VB 10.0 Collection Initializers

VB 10.0 Collection Initializers

Introduction

Collection Initializers是VB.NET 10.0的特色之一,讓我們能在宣告集合物件的同時塞入集合成員資料。

 

Support

  • VB 10.0 or latter

 

Collection Initializers

在VB.NET 9.0(含)以前,當我們想宣告集合物件並塞入集合成員資料,我們必需先宣告集合物件,接著使用Add把集合成員資料塞入集合物件。


        Dim list = New List(Of String)
        list.Add("abc")
        list.Add("def")
        list.Add("ghi")

 

或用AddRange塞入集合成員資料。


        Dim list = New List(Of String)
        list.AddRange(New String() {"abc", "def", "ghi"})

 

但在VB.NET 10.0(含)以後,我們可以透過From關鍵字來達到相同的目的。就像下面這樣:


Dim list = New List(Of String) From {"abc", "def", "ghi"}

 

編譯器在編譯時會自動幫我們把程式拆解回本來用Add呼叫的樣子。同樣的,Dictionary類別也可以採用相同方式來初始化。


Dim list As New Dictionary(Of Integer, String) From {{1, "abc"}, {2, "def"}}

 

除此之外,我們也可以利用擴充方法增加Add副程式用來處理Collection Initializers的動作。

 


    Dim list As New List(Of Customer) From {
                                            {123, "Jonathan", "Aneja"},
                                            {456, "Lucian", "Wischik"},
                                            {789, "Paul", "Vick"}
                                           }

    Class Customer
        Property ID As Integer
        Property FirstName As String
        Property LastName As String
    End Class

    <Extension()>
    Sub Add(list As List(Of Customer),
            ID As Integer,
            FirstName As String,
            LastName As String)

        list.Add(New Customer With {
                                        .ID=ID,
                                        .FirstName=FirstName,
                                        .LastName=LastName
                                   })
    End Sub