当我 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/