问题
I have following code
var list = new List<IMyCustomType>();
list.Add(new MyCustomTypeOne());
list.Add(new MyCustomTypeTwo());
list.Add(new MyCustomTypeThree());
this of course works, but I'm wondering: how can I declare the list and populate it with values using one statement?
Thanks
回答1:
var list = new List<IMyCustomType>{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
Edit: Asker changed "one line" to "one statement", and this looks nicer.
回答2:
var list = new List<IMyCustomType>
{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
Not quite sure why you want it in one line?
回答3:
use the collection initialiser
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},
}
回答4:
You can use a collection initializor:
var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
回答5:
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new MyCustomTypeTwo() };
来源:https://stackoverflow.com/questions/16711970/declare-a-list-and-populate-with-values-using-one-code-statement