c# - 列表属性的初始化语法

标签 c#

在用 List 作为属性初始化类时,我目睹了一些奇怪的事情。这样做的时候

var stuff = new Stuff(){list = {1, 2, 3} };

它编译,然后崩溃并提示列表为空。因此,将其添加到 Stuff 的构造函数中:

public Stuff(){
    list = new List<int>();
}

List 现在已初始化为包含 {1, 2, 3} 这似乎有些道理。但是,将构造函数更改为

public Stuff(){
    list = new List<int>(){1, 2, 3};
}

然后像这样初始化

var stuff = new Stuff(){list = {4, 5, 6} };

列表已初始化为包含 {1, 2, 3, 4, 5, 6} 让我很困惑。

这似乎不应该编译,或者不应该以这种方式运行。这里到底发生了什么?

最佳答案

It seems like this either shouldn't compile, or shouldn't behave this way. What exactly is going on here?

集合初始化器通过调用传递给初始化器的每个项目的 .Add 方法来工作。这它们添加到您在构造函数中预先填充的项目。

这在 the documentation for Collection Initializers 中有解释:

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

这意味着编译器将您的第二次调用变成类似于:

var temp = new Stuff();
temp.list.Add(4);
temp.list.Add(5);
temp.list.Add(6);
Stuff stuff = temp;

如您所见,stuff 变量将正常调用构造函数(添加123),然后添加其他项目,结果就是您所看到的。

关于c# - 列表属性的初始化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694553/

相关文章:

c# - (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault) 导致转换错误

C#,基于套接字通信的二进制序列化

c# - WCF web服务和getJSON为跨域调用返回空数据

c# - 限制属性的字符串长度

c# - LINQ 执行查询

c# - 在带有 MVC 3 的 ELMAH 中,如何从错误日志中隐藏敏感表单数据?

c# - 执行并行任务 -> 等待所有任务 -> 使用结果

c# - Quartz 中是否有有意义的 ITrigger.ToString() 方法?

java - TimePicker 在获取分钟和小时时导致应用程序崩溃

c# - 在 C# 中使用非托管 FindFirstVolume 通过 .NET 枚举卷