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 Chat 中使用的示例提示。
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 之前,请查看 Copilot 的建议。
有关 GitHub Copilot 的详细信息,请参阅 GitHub 的 常见问题解答。