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

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

    Override IDictionary for the C# 6.0 syntax

    In case someone comes here, as I did, looking to save some keystrokes for the new C# 6.0 dictionary initializer syntax, it can be done, but requires deriving from IDictionary instead. You only need to implement the this[] set method to get this to work, which leaves a ton of non-implemented methods.

    The class implementation looks like this:

    // Seriously!  Don't do this in production code! Ever!!!
    public class CrazyAdd2 : IDictionary
    {
        public int this[string key]
        {
            get { throw new NotImplementedException(); }
            set {Console.WriteLine($"([{key}]={value})"); }
        }
    
    #region NotImplemented
    // lots of empty methods go here
    #endregion
    }
    

    then to use it:

    var crazyAdd2 = new CrazyAdd2
    {
        ["one"] = 1,
        ["two"] = 2,
    };
    

    and the output:

    ([one]=1)
    ([two]=2)
    

    And here's a fiddle demonstrating the whole thing:

    https://dotnetfiddle.net/Lovy7m

提交回复
热议问题