这是 .NET 中集合初始值设定项语法的一部分。您可以在您创建的任何集合上使用此语法,只要:
调用默认构造函数,然后为初始化程序的每个成员调用Add(...)。
因此,这两个块大致相同:
List<int> a = new List<int> { 1, 2, 3 };
和
List<int> temp = new List<int>();
temp.Add(1);
temp.Add(2);
temp.Add(3);
List<int> a = temp;
如果需要,您可以调用备用构造函数,例如防止在增长过程中过度调整 List<T> 的大小等:
// Notice, calls the List constructor that takes an int arg
// for initial capacity, then Add()'s three items.
List<int> a = new List<int>(3) { 1, 2, 3, }
请注意,Add() 方法不必采用单个项目,例如 Dictionary<TKey, TValue> 的 Add() 方法采用两个项目:
var grades = new Dictionary<string, int>
{
{ "Suzy", 100 },
{ "David", 98 },
{ "Karen", 73 }
};
大致等同于:
var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;
因此,要将它添加到您自己的类中,您需要做的就是实现IEnumerable(同样,最好是IEnumerable<T>)并创建一个或多个Add() 方法:
public class SomeCollection<T> : IEnumerable<T>
{
// implement Add() methods appropriate for your collection
public void Add(T item)
{
// your add logic
}
// implement your enumerators for IEnumerable<T> (and IEnumerable)
public IEnumerator<T> GetEnumerator()
{
// your implementation
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
然后你可以像 BCL 集合一样使用它:
public class MyProgram
{
private SomeCollection<int> _myCollection = new SomeCollection<int> { 13, 5, 7 };
// ...
}
(有关详细信息,请参阅MSDN)