我有以下代码
var list = new List<IMyCustomType>();
list.Add(new MyCustomTypeOne());
list.Add(new MyCustomTypeTwo());
list.Add(new MyCustomTypeThree());
这当然有效,但我想知道:如何声明列表并使用一个语句填充值?
谢谢
我有以下代码
var list = new List<IMyCustomType>();
list.Add(new MyCustomTypeOne());
list.Add(new MyCustomTypeTwo());
list.Add(new MyCustomTypeThree());
这当然有效,但我想知道:如何声明列表并使用一个语句填充值?
谢谢
var list = new List<IMyCustomType>{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
编辑:Asker 将“一行”更改为“一个语句”,这看起来更好。
var list = new List<IMyCustomType>
{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
不太清楚为什么要在一行中使用它?
使用集合初始化程序
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},
}
您可以使用集合初始化器:
var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new MyCustomTypeTwo() };