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

标签 c# collection-initializer

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

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.

(强调我的)

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

关于c# - 列表属性的空集合初始值设定项导致 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084634/

相关文章:

c# - 多对多关系基本示例 (MVC3)

c# - 将集合初始值设定项与插入语句一起使用

c# - 集合初始化表达式的这两种变体有什么区别?

c# - OnTriggerEnter 不适用于 Unity3D

c# - 防止在字典中重复查找相同元素

c# - 在自定义类型上使用集合初始化语法?

c# - 初始化类的集合成员

使用 foreach 循环的 C# List 或 Collection 初始值设定项

c# - 具有嵌套值 : Cannot create instance of type because it is either abstract or an interface 的 IOptionsSnapshot

c# - Fluent NHibernate - 如何使用鉴别器创建每个子类的表映射?