为什么我们有时在初始化时不使用括号?

时间:2017-05-25 22:19:42

标签: c# list initialization

首先:

List <string> candidates = new List <string> {"person1", "person2"};

第二

Queue <int> myQueue = new Queue <int>(new int [] {0, 1, 2, 3, 4});

为什么我们在初始化新列表时不使用括号,但我们是为队列还是堆栈做的?

1 个答案:

答案 0 :(得分:1)

通过该列表,您可以利用名为&#34; Collection initializers&#34;的功能,您可以在此处阅读: https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

基本上,要工作,它取决于实现IEnumerable接口的集合并且具有&#34; Add&#34;方法(队列没有),或者,有一个可达的扩展方法叫做&#34; Add&#34; (您可以自己为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);
        }
    }
相关问题