字典初始值设定项相比集合初始值设定项有什么好处? [英] What benefits does dictionary initializers add over collection initializers?
问题描述
最近有很多关于 C# 6.0 新特性的讨论
最受关注的功能之一是在 C# 6.0 中使用 Dictionary
初始化程序
但是等等,我们一直在使用集合初始化器来初始化集合,并且在 .NET 4.0 和 .NET 4.5(不知道旧版本)中也可以很好地初始化 Dictionary
像
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.
字典初始化器更简洁:
var myDict = new Dictionary<int, string>
{
[1] = "Pankaj",
[2] = "Pankaj",
[3] = "Pankaj"
};
更重要的是,这些初始化器不仅仅用于字典,它们还可以用于任何支持索引器的对象,例如List
:
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
这篇关于字典初始值设定项相比集合初始值设定项有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!