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

C# 为什么我们在初始化时有时不使用括号?,c#,list,initialization,C#,List,Initialization,第一: List候选者=新列表{“person1”、“person2”}; 第二: List <string> candidates = new List <string> {"person1", "person2"}; Queue myQueue=new Queue(new int[]{0,1,2,3,4}); 为什么我们在初始化新列表时不使用括号,而在队列或堆栈中使用括号?对于列表,您正在利用一种称为“集合初始值设定项”的功能,您可以在此处阅读: 基本上,要工

第一:

List候选者=新列表{“person1”、“person2”};
第二:

List <string> candidates = new List <string> {"person1", "person2"};
Queue myQueue=new Queue(new int[]{0,1,2,3,4});

为什么我们在初始化新列表时不使用括号,而在队列或堆栈中使用括号?

对于列表,您正在利用一种称为“集合初始值设定项”的功能,您可以在此处阅读:

基本上,要工作,它取决于实现IEnumerable接口的集合是否有一个“Add”方法(队列没有),或者是否有一个名为“Add”的可访问扩展方法(您可以为队列自行实现)

静态类队列扩展
{
公共静态无效测试()
{
//请参阅,由于下面的扩展方法,现在队列还可以利用集合初始值设定项语法。
var queue=新队列{1,2,3,5};
}
公共静态void Add(此队列,T元素)
{
队列。排队(元素);
}
}

这里可以找到更详细的解释:它们在第一条语句中是可选的。只需添加它们,您就不必问这个问题:
newlist(){…}
也是查看这两个语句没有任何共同点的最佳方法。
Queue <int> myQueue = new Queue <int>(new int [] {0, 1, 2, 3, 4});
    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);
        }
    }