从C#6开始,可以通过在方括号中指定要分配的索引,后跟等号和要分配的值来初始化带有索引器的集合。
使用字典的这种语法的示例:
var dict = new Dictionary<string, int>
{
["key1"] = 1,
["key2"] = 50
};这等效于:
var dict = new Dictionary<string, int>(); dict["key1"] = 1; dict["key2"] = 50
在C#6之前执行此操作的集合初始化程序语法为:
var dict = new Dictionary<string, int>
{
{ "key1", 1 },
{ "key2", 50 }
};对应于:
var dict = new Dictionary<string, int>();
dict.Add("key1", 1);
dict.Add("key2", 50);因此,功能上存在重大差异,因为新语法使用初始化对象的索引器分配值而不是使用其Add()方法。这意味着新语法仅需要一个公共可用的索引器,并且适用于具有一个索引器的任何对象。
public class IndexableClass
{
public int this[int index]
{
set
{
Console.WriteLine("{0} was assigned to index {1}", value, index);
}
}
}
var foo = new IndexableClass
{
[0] = 10,
[1] = 20
}这将输出:
10 was assigned to index 0
20 was assigned to index 1