C#6.0的新字典初始化程序-澄清 [英] C# 6.0's new Dictionary Initializer - Clarification

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

问题描述

我读过:

团队通常忙于实施其他变体 初始值设定项.例如,您现在可以初始化一个Dictionary对象

The team have generally been busy implementing other variations on initializers. For example you can now initialize a Dictionary object

但请注意:

var Dic = new Dictionary<string,int>{ {"x",3}, {"y",7} };

vs.

var Dic = new Dictionary<string,int>{ ["x"]=3, ["y"]=7 };

我看不出好处在哪里.看起来一样.两者都不过是一个名称-值集合.
他们将花括号换成方括号和一些逗号

I don't see where the benefit is. It looks the same. Both are nothing more than a name-value collection.
They swapped pairs of curly braces for pairs of square brackets and some commas

问题:

使用新语法的附加值是什么?一个真实的例子将不胜感激.

What is the added value for using the new syntax ? A real world example would be much appreciated.

推荐答案

使用字典的主要优点是一致性.使用字典,初始化看起来与用法不同.

The main advantage here with a dictionary is consistency. With a dictionary, initialization did not look the same as usage.

例如,您可以这样做:

var dict = new Dictionary<int,string>();
dict[3] = "foo";
dict[42] = "bar";

但是使用初始化语法,您必须使用花括号:

But using initialization syntax, you had to use braces:

var dict = new Dictionary<int,string>
{
    {3, "foo"},
    {42, "bar"}
};

新的C#6索引初始化语法使初始化语法与索引用法更加一致:

The new C# 6 index initialization syntax makes initialization syntax more consistent with index usage:

var dict = new Dictionary<int,string>
{ 
    [3] = "foo",
    [42] = "bar"
};

但是,更大的好处是此语法还提供了允许您初始化其他类型的好处.任何带有索引器的类型都将允许通过此语法进行初始化,其中旧的集合初始化器仅适用于实现IEnumerable<T>且具有Add方法的类型.碰巧可以使用Dictionary<TKey,TValue>,但这并不意味着它可以用于任何基于索引的类型.

However, a bigger advantage is that this syntax also provides the benefit of allowing you to initialize other types. Any type with an indexer will allow initialization via this syntax, where the old collection initializers only works with types that implement IEnumerable<T> and have an Add method. That happened to work with a Dictionary<TKey,TValue>, but that doesn't mean that it worked with any index based type.

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

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