Why is an Add method required for { } initialization?

前端 未结 9 2129
渐次进展
渐次进展 2021-02-10 18:54

To use initialization syntax like this:

var contacts = new ContactList
{
    { \"Dan\", \"dan.tao@email.com\" },
    { \"Eric\", \"ceo@google.com\" }
};
<         


        
9条回答
  •  灰色年华
    2021-02-10 19:05

    As far as I understand it, the collection initializer syntax is just syntactic sugar with no special tricks in it. It was designed in part to support initializing collections inside Linq queries:

    from a in somewhere
    select new {
       Something = a.Something
       Collection = new List() {
          a.Item1,
          a.Item2,
          ...
       }
    }
    
    
    

    Before there was no way to do this inline and you'd have to do it after the case, which was annoying.

    提交回复
    热议问题