C#6的新的集合初始化 - 澄清? [英] C#6's new Collection Initializer - Clarification?

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

问题描述

我读过的:

球队一般都忙于实施上
初始化其他变化。例如,您现在可以初始化一个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

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> 并有一个添加方法。这事与词典<工作; 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的新的集合初始化 - 澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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