Why can I initialize a List like an array in C#?

前端 未结 6 1014
清歌不尽
清歌不尽 2020-12-12 23:20

Today I was surprised to find that in C# I can do:

List a = new List { 1, 2, 3 };

Why can I do this? What constructor

6条回答
  •  半阙折子戏
    2020-12-12 23:49

    This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:

    • It implements IEnumerable (preferably IEnumerable)

    • It has a method named Add(...)

    What happens is the default constructor is called, and then Add(...) is called for each member of the initializer.

    Thus, these two blocks are roughly identical:

    List a = new List { 1, 2, 3 };
    

    And

    List temp = new List();
    temp.Add(1);
    temp.Add(2);
    temp.Add(3);
    List a = temp;
    

    You can call an alternate constructor if you want, for example to prevent over-sizing the List during growing, etc:

    // Notice, calls the List constructor that takes an int arg
    // for initial capacity, then Add()'s three items.
    List a = new List(3) { 1, 2, 3, }
    

    Note that the Add() method need not take a single item, for example the Add() method for Dictionary takes two items:

    var grades = new Dictionary
        {
            { "Suzy", 100 },
            { "David", 98 },
            { "Karen", 73 }
        };
    

    Is roughly identical to:

    var temp = new Dictionary();
    temp.Add("Suzy", 100);
    temp.Add("David", 98);
    temp.Add("Karen", 73);
    var grades = temp;
    

    So, to add this to your own class, all you need do, as mentioned, is implement IEnumerable (again, preferably IEnumerable) and create one or more Add() methods:

    public class SomeCollection : IEnumerable
    {
        // implement Add() methods appropriate for your collection
        public void Add(T item)
        {
            // your add logic    
        }
    
        // implement your enumerators for IEnumerable (and IEnumerable)
        public IEnumerator GetEnumerator()
        {
            // your implementation
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

    Then you can use it just like the BCL collections do:

    public class MyProgram
    {
        private SomeCollection _myCollection = new SomeCollection { 13, 5, 7 };    
    
        // ...
    }
    

    (For more information, see the MSDN)

提交回复
热议问题