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

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

    Your problem stems from the fact that it is an array, not a collection.

    var kvps = new KeyValuePair[] {
        { "key1", 1 },
        { "key2", 2 }
    };
    

    should really be:

    var kvps = new KeyValuePair[] {
        new KeyValuePair("key1", 1),
        new KeyValuePair("key2", 2)
    };
    

    The giveaway is the brackets. [] is an array. {} is a collection.

提交回复
热议问题