码迷,mamicode.com
首页 > Windows程序 > 详细

C# 6.0:新的Dictionary Initializer

时间:2014-12-19 12:01:44      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   使用   sp   

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

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

bubuko.com,布布扣
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列表,如下图所示:

bubuko.com,布布扣

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

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

bubuko.com,布布扣

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

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

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

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

bubuko.com,布布扣

C# 6.0:新的Dictionary Initializer

标签:style   blog   http   ar   io   color   os   使用   sp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!