在用 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
变量将正常调用构造函数(添加1
、2
和3
),然后添加其他项目,结果就是您所看到的。
关于c# - 列表属性的初始化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694553/