简体   繁体   English

C#初始化列表集合

[英]C# initializing List Collection

I have always initialized a collection as such:- 我总是这样初始化一个集合:

List<Type> name = new List<Type>();

But today I saw something like this:- 但是今天我看到这样的东西:

var variablename = new sMonth{
    x = foo;
    name = new List<Type>()
};

Is that even possible? 那有可能吗? and what is the difference between the two ways? 两种方式有什么区别?

Yes, your second snippet is an example of object initialization . 是的,您的第二个片段是对象初始化的示例。

Assuming your sMonth object contains a property of type List<Type> , you can initialize the object at the point you create the outer object: 假设您的sMonth对象包含类型为List<Type>的属性,则可以在创建外部对象时初始化该对象:

var variablename = new sMonth{
    x = foo,
    name = new List<Type>()
};

Note the comma between items. 注意项目之间的逗号。

Additionally, since you're not assigning anything to name you could use the sMonth constructor to initialize the collection for you: 此外,由于没有给name分配任何内容,因此可以使用sMonth构造函数为您初始化集合:

public sMonth()
{
    name = new List<Type>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM