声明一个列表并使用一条代码语句填充数值

15

我有以下的代码

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

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

谢谢


2
使用文档:http://msdn.microsoft.com/zh-cn/library/vstudio/bb384062.aspx。不使用文档扣1分 ;) - Leri
你可以把 var list = new List<IMyCustomType>(); list.Add(new MyCustomTypeOne()); list.Add(new MyCustomTypeTwo()); list.Add(new MyCustomTypeThree()); 放在一行上。或者你是指 一个语句 - David Heffernan
@DavidHeffernan :) 当然,只有一句话。 - user1765862
但这不是你说的。请准确表述。请编辑问题。 - David Heffernan
5个回答

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

编辑:提问者将“一行”更改为“一条语句”,这看起来更好。


9
var list = new List<IMyCustomType>
{
   new MyCustomTypeOne(),
   new MyCustomTypeTwo(),
   new MyCustomTypeThree()
};
不太确定为什么您希望将其放在一行中?

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},
}

2
您可以使用一个集合初始化器:(collection initializor)
var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接