集合初始設定式 (Visual Basic)Collection Initializers (Visual Basic)

「集合初始設定式」提供簡短的語法,以讓您建立集合,並填入一組初始值。Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. 當您透過一組已知值來建立集合時,集合初始設定式十分有用,例如,一份功能表選項或類別清單、一組初始數值、一份日期或月份名稱這類靜態字串清單,或用於驗證的這類省市清單的地理位置。Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories, an initial set of numeric values, a static list of strings such as day or month names, or geographic locations such as a list of states that is used for validation.

如需集合的詳細資訊,請參閱集合For more information about collections, see Collections.

您可以使用後面接著大括弧 ({}) 的 From 關鍵字,來識別集合初始設定式。You identify a collection initializer by using the From keyword followed by braces ({}). 這類似陣列中所述的陣列常值語法。This is similar to the array literal syntax that is described in Arrays. 下列範例顯示使用集合初始設定式建立集合的各種方式。The following examples show various ways to use collection initializers to create collections.

' Create an array of type String().
Dim winterMonths = {"December", "January", "February"}

' Create an array of type Integer()
Dim numbers = {1, 2, 3, 4, 5}

' Create a list of menu options. (Requires an extension method
' named Add for List(Of MenuOption)
Dim menuOptions = New List(Of MenuOption) From {{1, "Home"},
                                                {2, "Products"},
                                                {3, "News"},
                                                {4, "Contact Us"}}

注意

C# 也提供集合初始設定式。C# also provides collection initializers. C# 集合初始設定式所提供的功能與 Visual Basic 集合初始設定式相同。C# collection initializers provide the same functionality as Visual Basic collection initializers. 如需 C# 集合初始設定式的詳細資訊,請參閱物件和集合初始設定式For more information about C# collection initializers, see Object and Collection Initializers.

語法Syntax

集合初始設定式包含逗號分隔值清單,而這些值以大括弧 ({}) 括住而且前面加上 From 關鍵字,如下列程式碼所示。A collection initializer consists of a list of comma-separated values that are enclosed in braces ({}), preceded by the From keyword, as shown in the following code.

Dim names As New List(Of String) From {"Christa", "Brian", "Tim"}

當您建立 List<T>Dictionary<TKey,TValue> 這類集合時,必須在集合初始設定式之前提供集合類型,如下列程式碼所示。When you create a collection, such as a List<T> or a Dictionary<TKey,TValue>, you must supply the collection type before the collection initializer, as shown in the following code.

Public Class AppMenu
    Public Property Items As List(Of String) =
        New List(Of String) From {"Home", "About", "Contact"}
End Class

注意

您無法合併使用集合初始設定式與物件初始設定式來初始化相同的集合物件。You cannot combine both a collection initializer and an object initializer to initialize the same collection object. 您可以使用物件初始設定式來初始化集合初始設定式中的物件。You can use object initializers to initialize objects in a collection initializer.

使用集合初始設定式建立集合Creating a Collection by Using a Collection Initializer

當您使用集合初始設定式建立集合時,集合初始設定式中所提供的每個值都會傳遞給集合的適當 Add 方法。When you create a collection by using a collection initializer, each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection. 例如,如果您使用集合初始設定式建立 List<T>,則會將集合初始設定式中的每個字串值傳遞給 Add 方法。For example, if you create a List<T> by using a collection initializer, each string value in the collection initializer is passed to the Add method. 如果您想要使用集合初始設定式建立集合,則指定的類型必須是有效的集合類型。If you want to create a collection by using a collection initializer, the specified type must be valid collection type. 有效集合類型的範例包括可實作 IEnumerable<T> 介面或繼承 CollectionBase 類別的類別。Examples of valid collection types include classes that implement the IEnumerable<T> interface or inherit the CollectionBase class. 指定的類型也必須公開符合下列準則的 Add 方法。The specified type must also expose an Add method that meets the following criteria.

  • Add 方法必須可從將在其中呼叫集合初始設定式的範圍使用。The Add method must be available from the scope in which the collection initializer is being called. 如果您在可存取集合之非公開方法的情況下使用集合初始設定式,則 Add 方法不一定要是公開的。The Add method does not have to be public if you are using the collection initializer in a scenario where non-public methods of the collection can be accessed.

  • Add 方法必須是集合類別的執行個體成員或 Shared 成員或是擴充方法。The Add method must be an instance member or Shared member of the collection class, or an extension method.

  • 根據多載解析規則,Add 方法必須要符合集合初始設定式中所提供的類型。An Add method must exist that can be matched, based on overload resolution rules, to the types that are supplied in the collection initializer.

例如,下列程式碼範例示範如何使用集合初始設定式,來建立 List(Of Customer) 集合。For example, the following code example shows how to create a List(Of Customer) collection by using a collection initializer. 程式碼執行時,每個 Customer 物件都會傳遞給泛型清單的 Add(Customer) 方法。When the code is run, each Customer object is passed to the Add(Customer) method of the generic list.

Dim customers = New List(Of Customer) From
    {
        New Customer("City Power & Light", "http://www.cpandl.com/"),
        New Customer("Wide World Importers", "http://www.wideworldimporters.com/"),
        New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/")
    }

下列程式碼範例示範未使用集合初始設定式的對等程式碼。The following code example shows equivalent code that does not use a collection initializer.

Dim customers = New List(Of Customer) 
customers.Add(New Customer("City Power & Light", "http://www.cpandl.com/"))
customers.Add(New Customer("Wide World Importers", "http://www.wideworldimporters.com/"))
customers.Add(New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/"))

如果集合的 Add 方法具有與 Customer 物件建構函式相符的參數,則可以將 Add 方法的參數值巢狀在集合初始設定式內,如下節所述。If the collection has an Add method that has parameters that match the constructor for the Customer object, you could nest parameter values for the Add method within collection initializers, as discussed in the next section. 如果集合沒有這類 Add 方法,您可以建立此方法作為擴充方法。If the collection does not have such an Add method, you can create one as an extension method. 如需如何建立的範例Add方法作為擴充方法的集合,請參閱How to:建立 Add 擴充方法,集合初始設定式使用For an example of how to create an Add method as an extension method for a collection, see How to: Create an Add Extension Method Used by a Collection Initializer. 如需如何建立自訂的集合,可以搭配集合初始設定式的範例,請參閱How to:建立集合,集合初始設定式使用For an example of how to create a custom collection that can be used with a collection initializer, see How to: Create a Collection Used by a Collection Initializer.

巢狀集合初始設定式Nesting Collection Initializers

您可以將值巢狀在集合初始設定式內,以識別所建立集合之 Add 方法的特定多載。You can nest values within a collection initializer to identify a specific overload of an Add method for the collection that is being created. 傳遞給 Add 方法的值必須以逗號區隔,並用大括弧 ({}) 括住,就像在陣列常值或集合初始設定式中一樣。The values passed to the Add method must be separated by commas and enclosed in braces ({}), like you would do in an array literal or collection initializer.

當您使用巢狀值來建立集合時,巢狀值清單的每個項目都會傳遞為符合項目類型之 Add 方法的引數。When you create a collection by using nested values, each element of the nested value list is passed as an argument to the Add method that matches the element types. 例如,下列程式碼範例會建立 Dictionary<TKey,TValue>其中,索引鍵的類型為 Integer,而值的類型為 StringFor example, the following code example creates a Dictionary<TKey,TValue> in which the keys are of type Integer and the values are of type String. 每個巢狀值清單都會對應到 DictionaryAdd 方法。Each of the nested value lists is matched to the Add method for the Dictionary.

Dim days = New Dictionary(Of Integer, String) From
    {{0, "Sunday"}, {1, "Monday"}}

先前的程式碼範例等同於下列程式碼。The previous code example is equivalent to the following code.

Dim days = New Dictionary(Of Integer, String)
days.Add(0, "Sunday")
days.Add(1, "Monday")

只會將第一層巢狀層的巢狀值清單傳送至集合類型的 Add 方法。Only nested value lists from the first level of nesting are sent to the Add method for the collection type. 更深入的巢狀層會視為陣列常值,而且巢狀值清單不會對應到任何集合的 Add 方法。Deeper levels of nesting are treated as array literals and the nested value lists are not matched to the Add method of any collection.

標題Title 說明Description
如何:建立新增為集合初始設定式所使用的擴充方法How to: Create an Add Extension Method Used by a Collection Initializer 示範如何建立稱為 Add 的擴充方法,以用來將集合初始設定式中的值填入集合。Shows how to create an extension method called Add that can be used to populate a collection with values from a collection initializer.
如何:建立集合,集合初始設定式使用How to: Create a Collection Used by a Collection Initializer 示範如何將 Add 方法包括在可實作 IEnumerable 的集合類別中,以啟用集合初始設定式。Shows how to enable use of a collection initializer by including an Add method in a collection class that implements IEnumerable.

另請參閱See also