今天我惊讶地发现在 C# 中我可以做到:
List<int> a = new List<int> { 1, 2, 3 };
为什么我可以这样做?调用什么构造函数?我怎样才能用我自己的类(class)做到这一点?我知道这是初始化数组的方法,但数组是语言项而列表是简单对象 ...
最佳答案
这是 .NET 中集合初始化器语法的一部分。您可以在您创建的任何集合上使用此语法,只要:
它实现了
IEnumerable
(最好是IEnumerable<T>
)它有一个名为
Add(...)
的方法
会发生什么是调用默认构造函数,然后 Add(...)
为初始化程序的每个成员调用。
因此,这两个 block 大致相同:
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()
方法不需要采用单个项目,例如 Add()
Dictionary<TKey, TValue>
的方法需要两个项目:
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)
关于c# - 为什么我可以在 C# 中像数组一样初始化一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853937/