问题描述
当我,它不初始化 ThisIsAList
来一个空的集合作为我期待......而不是 ThisIsAList
为null。
When I run this code, it doesn't initialize ThisIsAList
to an empty collection as I was expecting... instead ThisIsAList
was null.
void Main()
{
var thing = new Thing
{
ThisIsAList = {}
};
Console.WriteLine(thing.ThisIsAList == null); // prints "True"
}
public class Thing
{
public List<string> ThisIsAList { get; set; }
}
为什么不是这样的编译错误?为什么空
?
我在想,如果可能的结果有一个隐式转换会在这里,但下面的尝试产生编译错误:
I was wondering if maybe there was an implicit conversion going on here, but the following attempts produced compile errors:
thing.ThisIsAList = Enumerable.Empty<string>().ToArray();
List<int> integers = { 0, 1, 2, 3 };
据上的的,这听起来像一个集合初始化基本上只是处理电话添加()
为你。所以,
我寻找可能的过载到,但没有发现任何东西,我认为也适用。
According to MSDN documenation on collection initializers, it sounds like a collection initializer basically just handles calling Add()
for you. SoI looked for possible overloads to List.Add
, but didn't find anything that I think would apply.
有人能解释?什么是从C#规范怎么回事
Can someone explain what's going on here from the C# spec?
推荐答案
在部分C#5.0规范的7.6.10.2:
In section 7.6.10.2 of the C# 5.0 specs:
这是指定集合初始化后等号成员初始化是嵌入集合的初始化。 除了到外地或财产分配一个新的集合,在初始化中给出的元素添加到由外地或财产引用的集合。该字段或属性必须满足在§7.6.10.3规定的要求的集合类型。
(重点煤矿)
所以,因为你的集合初始化嵌套在另一个对象/集合初始化器内的行为是它解决它initialzing一个值的成员,然后将相关项目。在这种情况下,该属性是空
,使空
价值得到解决,并在初始化所有零项目添加。如果你真的想增加一个项目,它会抛出一个NRE,因为你会试图将项目添加到空
对象。
So since your collection initializer is nested inside of another object/collection initializer the behavior is that it resolves the member it is initialzing to a value, and then adds the relevant items. In this case, the property is null
, so that null
value is resolved, and all zero items in your initializer are added. If you actually tried to add an item, it'd throw a NRE since you'd be trying to add an item to a null
object.
这篇关于空集合初始化为空列表属性结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!