Why is an Add method required for { } initialization?

前端 未结 9 2125
渐次进展
渐次进展 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: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[] initialValues)
    

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

    So we need to use a workaround like

    MyClass(new KeyValuePair[]{...})
    

    for now

提交回复
热议问题