Why is an Add method required for { } initialization?

前端 未结 9 2126
渐次进展
渐次进展 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:17

    Collection initializers are expressions, so they can be used where only expression are valid, such as a field initializer or LINQ query. This makes their existence very useful.

    I also think the curly-bracketed { } kind of initialization, smells more like a fixed size collection, but it's just a syntax choice.

    0 讨论(0)
  • 2021-02-10 19:19

    The reason for this is that it was retrofitted. I agree with you that using a constructor taking a collection would make vastly more sense, but not all of the existing collection classes implemented this and the change should (1) work with all existing collections, (2) not change the existing classes in any way.

    It’s a compromise.

    0 讨论(0)
  • 2021-02-10 19:22

    I'd love to have the initializer syntax for immutable types(both collections and normal types). I think this could be implemented with a special constructor overload using a syntax similar to params.

    For example something like this:

    MyClass(initializer KeyValuePair<K,V>[] initialValues)
    

    But unfortunately the C# team didn't implement such a thing yet :(

    So we need to use a workaround like

    MyClass(new KeyValuePair<K,V>[]{...})
    

    for now

    0 讨论(0)
提交回复
热议问题