Why can I initialize a List like an array in C#?

前端 未结 6 1007
清歌不尽
清歌不尽 2020-12-12 23:20

Today I was surprised to find that in C# I can do:

List a = new List { 1, 2, 3 };

Why can I do this? What constructor

6条回答
  •  攒了一身酷
    2020-12-12 23:38

    It is so called syntactic sugar.

    List is the "simple" class, but compiler gives a special treatment to it in order to make your life easier.

    This one is so called collection initializer. You need to implement IEnumerable and Add method.

提交回复
热议问题