C#6.0新功能字典初始化程序 [英] C# 6.0 New Feature Dictionary Initializers

查看:329
本文介绍了C#6.0新功能字典初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的过去,有很多关于C#6.0中的新功能的讨论。

最热门的功能之一是使用 Dictionary 初始化器在C#6.0

但是,等待我们已经使用收集初始化器初始化集合,并可以非常好地初始化一个字典也在.NET 4.0和。 NET 4.5(不知道旧版本)如

In a recent past there has been a lot of talk about whats new in C# 6.0
One of the most talked about feature is using Dictionary initializers in C# 6.0
But wait we have been using collection initializers to initialize the collections and can very well initialize a Dictionary also in .NET 4.0 and .NET 4.5 (Don't know about old version) like

Dictionary<int, string> myDict = new Dictionary<int, string>() {
    { 1,"Pankaj"},
    { 2,"Pankaj"},
    { 3,"Pankaj"}
};

因此,在C#6.0中有什么新的,他们在C#6.0中谈论什么字典初始化程序


So what is there new in C# 6.0, What Dictionary Initializer they are talking about in C# 6.0

推荐答案

当您可以使用集合初始化函数初始化字典时,这很麻烦。

While you could initialize a dictionary with collection initializers, it's quite cumbersome. Especially for something that's supposed to be syntactic sugar.

字典初始化程序非常干净:

Dictionary initializers are much cleaner:

var myDict = new Dictionary<int, string>
{
    [1] = "Pankaj",
    [2] = "Pankaj",
    [3] = "Pankaj"
};

更重要的是,这些初始化器不仅仅用于字典,它们可以用于任何对象支持索引器,例如 List< T>

More importantly these initializers aren't just for dictionaries, they can be used for any object supporting an indexer, for example List<T>:

var array = new[] { 1, 2, 3 };
var list = new List<int>(array) { [1] = 5 };
foreach (var item in list)
{
    Console.WriteLine(item);
}

输出:

1
5
3

这篇关于C#6.0新功能字典初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆