C# 6.0:新的Dictionary Initializer

初始化Dictionary不是什么新东西,你可以简单的通过Collection Initializer来初始化一个Dictionary,这是从C#3.0就有的特性。Collection Initializer添加一个参数做key,一个参数作为对应key的value。C#6.0添加了一种在初始化中使用Key/indexer来将value直接映射key和value的能力。

下面的代码显示了Collection Initializer是怎样初始化Dictionary的。

Dictionary<int, string> students = new Dictionary<int, string> 
{
    {1, "Student 1" },
    {2, "Student 2" },
    {3, "Student 3" },
    {4, "Student 4" }
};
View Code

这会定义一个名为students的Dictionary对象,它有一个Key为int类型的students列表,如下图所示:

在C# 6.0种,使用新的Dictionary Initializer,下面的代码块也会实现同样的功效:

Dictionary<int, string> students = new Dictionary<int, string> 
{
    [1] = "Student 1" ,
    [2] = "Student 2",
    [3] = "Student 3",
    [4] = "Student 4",
};
View Code

上面的代码返回同样的结果,不同的是它们的赋值方法。在C#6.0中,看起来我们是通过indexer来获得它们。而这使代码变得更好理解。

现在,如果你想要给collection中添加新元素的话你可以使用下面的方法。

students[5] = "Student 5";
students[6] = "Student 6";

上面的代码会在dictionary中添加两个新的元素。

原文地址:https://www.cnblogs.com/yuwen/p/4173492.html