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

后端 未结 6 1802
滥情空心
滥情空心 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:19

    It does work with the Dictionary, because it has an overload for Add that takes two arguments. Arrays dont even have an Add method, let alone one with two arguments.

    The Dictionary class is specially designed to work with KeyValuePair<,> internally, that is the only reason you do not need the call the constructor manually, instead the two-argument Add is called and constructs the KeyValuePair under the hood.

    Every other IEnumerable> does not have this special implementation and therefore has to be initialized this way:

    var array = new KeyValuePair[] {
        new KeyValuePair(1, 2),
        new KeyValuePair(3, 4)
    };
    

    You can create the same behaviour with your own classes, like lets say you implement this:

    class ThreeTupleList : List>
    {
        public void Add(T1 a, T2 b, T3 c)
        {
            this.Add(new Tuple(a, b, c));
        }
    
        // You can even implement a two-argument Add and mix initializers
        public void Add(T1 a, T2 b)
        {
            this.Add(new Tuple(a, b, default(T3)));
        }
    }
    

    you can initialize it like this, and even mix three-, two- and one-argument initializers:

    var mylist = new ThreeTupleList()
    {
        { 1, "foo", 2.3 },
        { 4, "bar", 5.6 },
        { 7, "no double here" },
        null
    };
    

提交回复
热议问题