列表 属性 的空集合初始值设定项导致 null

Empty collection initializer for list property results in null

当我 run this code 时,它没有像我预期的那样将 ThisIsAList 初始化为空集合...相反 ThisIsAList 为空。

void Main()
{
    var thing = new Thing
    {
        ThisIsAList = {}
    };

    Console.WriteLine(thing.ThisIsAList == null); // prints "True"
}

public class Thing
{
    public List<string> ThisIsAList { get; set; }
}

为什么这不是编译错误?为什么结果是null?


我想知道这里是否进行了隐式转换,但以下尝试产生了编译错误:

thing.ThisIsAList = Enumerable.Empty<string>().ToArray();
List<int> integers = { 0, 1, 2, 3 };

根据 collection initializers 上的 MSDN 文档,这听起来像是一个集合初始化程序,基本上只是为您处理调用 Add()。所以 我寻找了 List.Add 的可能重载,但没有找到任何我认为适用的内容。

有人可以根据 C# 规范解释这里发生了什么吗?

在 C# 5.0 规范的第 7.6.10.2 节中:

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property. The field or property must be of a collection type that satisfies the requirements specified in §7.6.10.3.

(强调我的)

因此,由于您的集合初始值设定项嵌套在另一个 object/collection 初始值设定项中,其行为是它将正在初始化的成员解析为一个值,然后添加相关项。在这种情况下,属性 是 null,因此 null 值已解析,并且添加了初始化程序中的所有零项。如果您实际上尝试添加一个项目,它会抛出一个 NRE,因为您试图将一个项目添加到 null 对象。