c# - 从初始化器创建列表

标签 c# list initializer

有什么区别吗

var list = new List<UserType>
{
    new UserType(...),
    new UserType(...),
};

var list = new List<UserType>()
{
    new UserType(...),
    new UserType(...),
};

?

我过去总是使用第二个,认为我只需要调用列表的无参数(或任何其他)构造函数...

最佳答案

是一样的。来自 MSDN :

The object initializer syntax enables you to specify arguments for a constructor or omit the arguments (and parentheses syntax)

同样的规则适用于列表和普通对象初始值设定项:

var foo = new Bar {
    Prop = "value"
};

关于c# - 从初始化器创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21383499/

相关文章:

c++ - 如何使用常规构造函数模式初始化 C++ 11 标准容器?

c# - List.Foreach 在 Using block 中使用一次性项目

c# - MEF - 我是否需要实现 IPartImportsSatisfiedNotification

C 链表函数程序遇到段错误

python - 如何从列表中的整数中删除重复的数字

angular - APP_INITIALIZER阻止在错误时加载应用

c# - 将 for(;;) 循环变成 foreach

c# - 如何从 Visual Studio 调试输出窗口读取文本

python - 匹配新字典中的字典键和值

java - 为什么编译取决于实例初始化程序中抛出异常的方式?