What benefits does dictionary initializers add over collection initializers?

末鹿安然 提交于 2019-11-27 04:40:28

问题


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"}
};

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


回答1:


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"
};

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);
}

Output:

1
5
3



回答2:


New is creating a dictionary this way

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

with the style of <index> = <value>

Obsolete: string indexed member syntax (as stated in the comments)

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

Taken from A C# 6.0 Language Preview

To understand the $ operator, take a look at the AreEqual function call. Notice the Dictionary member invocation of “$Boolean” on the builtInDataTypes variable—even though there’s no “Boolean” member on Dictionary. Such an explicit member isn’t required because the $ operator invokes the indexed member on the dictionary, the equivalent of calling buildInDataTypes["Boolean"].



来源:https://stackoverflow.com/questions/27244132/what-benefits-does-dictionary-initializers-add-over-collection-initializers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!