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

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

    Thanks to multiple answerers for pointing out that the Add method is the magical thing secret sauce that makes the initialization syntax work. So I could achieve my goal by inheriting the class in question (KeyValuePair):

    public class InitializableKVPs : IEnumerable>
    {
        public void Add(T1 key, T2 value) 
        {
            throw new NotImplementedException();
        }
    
        public IEnumerator>  GetEnumerator()
        {
            throw new NotImplementedException();
        }
    
        IEnumerator  IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
    

    This now is accepted by the compiler:

    var kvps = new InitializableKVPs {
        { "key1", 1 },
        { "key2", 2 }
    };
    

    Edit: Philip Daubmeier's answer has an actual, concise implementation of this.

提交回复
热议问题