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
它們在第一條語句中是可選的。只需添加它們,所以你不必問這個問題:'新列表(){...};'也是看到這兩個語句沒有共同點的最好方法。 –