共用方式為


如何:使用集合初始設定式來初始化字典 (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 方法和兩個引數。 編譯器會針對每組 Add 索引鍵和 int 值產生對 StudentName 的呼叫。 第二個使用 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 作為物件初始設定式。

使用 AI 生成詞典集合的測試數據

您可以使用 AI 工具 (例如 GitHub Copilot) 在 C# 專案中快速產生字典測試資料和驗證案例。

以下是您可以在 Visual Studio Copilot 聊天中使用的範例提示。

Generate data collections for tests to create a separate Dictionary<int, Student> containing 10 valid Student records and 5 invalid records. 
- Valid records should have realistic Name and Grade values.
- Invalid records should include cases such as missing Name, Grade < 0, or Grade > 100. 
- This dictionary should be used only for testing purposes and not modify existing production code.
- Generate test code that utilizes this test data for validation scenarios.
- Call test method to run the test.

在應用之前查看 Copilot 的建議。

如需 GitHub Copilot 的詳細資訊,請參閱 GitHub 的 常見問題集

另請參閱