如何:使用集合初始設定式來初始化字典 (C# 程式設計手冊)

Dictionary<TKey,TValue> 包含索引鍵/值組的集合。 其 Add 方法採用兩個參數,其中之一供索引鍵之用,而另一個則供值之用。 若要初始化 Dictionary<TKey,TValue> 或任何其 Add 方法採用多個參數的所有集合,其中一個方式是將每個參數集以大括弧括住,如下列範例所示。 另一個選項是使用索引子初始設定式,也會顯示在下列範例中。

注意

這兩種初始化集合的方式之間的主要差別在於:在有重複索引鍵的情況下,例如:

{ 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
{ 111, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } }, 

Add 方法會擲回 ArgumentException'An item with the same key has already been added. Key: 111',而範例的第二個部分 (公用讀取/寫入索引器方法) 會以相同的索引鍵悄悄地覆寫已經存在的項目。

範例

在下列程式碼範例中,Dictionary<TKey,TValue> 會使用類型 StudentName 的執行個體進行初始化。 第一個初始化使用 Add 方法和兩個引數。 編譯器會針對每組 int 索引鍵和 StudentName 值產生 Add 呼叫。 第二個使用 Dictionary 類別的公用讀取/寫入索引子方法:

public class HowToDictionaryInitializer
{
    class StudentName
    {
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public int ID { get; set; }
    }

    public static void Main()
    {
        var students = new Dictionary<int, StudentName>()
        {
            { 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
            { 112, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } },
            { 113, new StudentName { FirstName="Andy", LastName="Ruth", ID=198 } }
        };

        foreach(var index in Enumerable.Range(111, 3))
        {
            Console.WriteLine($"Student {index} is {students[index].FirstName} {students[index].LastName}");
        }
        Console.WriteLine();		

        var students2 = new Dictionary<int, StudentName>()
        {
            [111] = new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 },
            [112] = new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } ,
            [113] = new StudentName { FirstName="Andy", LastName="Ruth", ID=198 }
        };

        foreach (var index in Enumerable.Range(111, 3))
        {
            Console.WriteLine($"Student {index} is {students2[index].FirstName} {students2[index].LastName}");
        }
    }
}

請注意,在第一個宣告中,該集合的每個項目中都有兩組大括弧。 最內層大括弧會括住 的物件初始化表達式 StudentName,而最外大括弧會括住要加入至 studentsDictionary<TKey,TValue>之索引鍵/值組的初始化表達式。 最後,會以括號括住目錄的整個集合初始設定式。 在第二個初始化中,指派左側是索引鍵,右側是其值,並使用 StudentName 的物件初始設定式。

另請參閱