Why is an Add method required for { } initialization?

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

    The main reason is Syntactic Sugar.

    The initializer syntax only makes writing programing in C# a bit easier. It doesn't actually add any expressive power to the language.

    If the initializer didn't require an Add() method, then it would be a much different feature than it is now. Basically, it's just not how C# works. There is no literal form for creating general collections.

提交回复
热议问题