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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16711970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:44:30  来源:igfitidea点击:

Declare a List and populate with values using one code statement

c#.netlistinitializer

提问by user1765862

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

谢谢

采纳答案by Colm Prunty

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

Edit: Asker changed "one line" to "one statement", and this looks nicer.

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

回答by David Hoerster

You can use a collection initializor:

您可以使用集合初始值设定项

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

回答by Jamie Dixon

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

回答by nik0lias

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

Not quite sure why you want it in one line?

不太确定为什么要在一行中使用它?

回答by Atish Dipongkor - MVP

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