11

我有以下代码

var list = new List<IMyCustomType>();
list.Add(new MyCustomTypeOne());
list.Add(new MyCustomTypeTwo());
list.Add(new MyCustomTypeThree());

这当然有效,但我想知道:如何声明列表并使用一个语句填充值?

谢谢

4

5 回答 5

17
var list = new List<IMyCustomType>{ 
    new MyCustomTypeOne(), 
    new MyCustomTypeTwo(), 
    new MyCustomTypeThree() 
};

编辑:Asker 将“一行”更改为“一个语句”,这看起来更好。

于 2013-05-23T10:50:40.240 回答
9
var list = new List<IMyCustomType>
{
   new MyCustomTypeOne(),
   new MyCustomTypeTwo(),
   new MyCustomTypeThree()
};

不太清楚为什么要在一行中使用它?

于 2013-05-23T10:51:24.483 回答
3

使用集合初始化程序

var list = new List<IMyCustomType>
{
   new MyCustomTypeOne(){Properties should be given here},
   new MyCustomTypeTwo(){Properties should be given here},
   new MyCustomTypeThree(){Properties should be given here},
}
于 2013-05-23T10:54:47.663 回答
2

您可以使用集合初始化器

var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
于 2013-05-23T10:51:09.953 回答
0
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new  MyCustomTypeTwo() };
于 2013-05-23T10:51:18.823 回答