How to make inline array initialization work like e.g. Dictionary initialization?

后端 未结 6 1808
滥情空心
滥情空心 2021-02-12 12:02

Why is it possible to initialize a Dictionary like this:

var dict = new Dictionary() { 
    { \"key1\", 1 },
    { \"         


        
6条回答
  •  独厮守ぢ
    2021-02-12 12:13

    The collection initializer syntax is translated into calls to Add with the appropriate number of parameters:

    var dict = new Dictionary();
    dict.Add("key1", 1);
    dict.Add("key2", 2);
    

    This special initializer syntax will also work on other classes that have an Add method and implements IEnumerable. Let's create a completely crazy class just to prove that there's nothing special about Dictionary and that this syntax can work for any suitable class:

    // Don't do this in production code!
    class CrazyAdd : IEnumerable
    {
        public void Add(int x, int y, int z)
        {
            Console.WriteLine(x + y + z); // Well it *does* add...
        }
    
        public IEnumerator GetEnumerator() { throw new NotImplementedException(); }
    }
    

    Now you can write this:

    var crazyAdd = new CrazyAdd
    {
        {1, 2, 3},
        {4, 5, 6}
    };
    

    Outputs:

    6
    15
    

    See it working online: ideone

    As for the other types you asked about:

    • It doesn't work on an array because it has no Add method.
    • List has an Add method but it has only one parameter.

提交回复
热议问题