List <string> candidates = new List <string> {"person1", "person2"};
二:
Queue <int> myQueue = new Queue <int>(new int [] {0, 1, 2, 3, 4});
,为什么我们不使用括号,同时初始化一个新的列表,但我们的队列或堆栈呢?
List <string> candidates = new List <string> {"person1", "person2"};
二:
Queue <int> myQueue = new Queue <int>(new int [] {0, 1, 2, 3, 4});
,为什么我们不使用括号,同时初始化一个新的列表,但我们的队列或堆栈呢?
随着名单,你正在服用一种叫做“集合初始化”功能的优势,你可以在这里读到它: https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
基本上,工作,这取决于实现IEnumerable接口和具有收藏一个“Add”方法(Queue没有),或者有一个称为“Add”的可达扩展方法(你可以为Queue实现)。
static class QueueExtensions
{
public static void Test()
{
// See that due to the extension method below, now queue can also take advantage of the collection initializer syntax.
var queue = new Queue<int> { 1, 2, 3, 5 };
}
public static void Add<T>(this Queue<T> queue, T element)
{
queue.Enqueue(element);
}
}
更详细的解释可以在这里找到:https://stackoverflow.com/questions/8853937/why-can-i-initialize-a-list-like-an-array-in-c – Timo
它们在第一条语句中是可选的。只需添加它们,所以你不必问这个问题:'新列表(){...};'也是看到这两个语句没有共同点的最好方法。 –