当我I 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 documenation,这听起来像一个集合初始基本只是为你处理呼叫Add()
。所以 我寻找可能的重载List.Add
,但没有找到任何我认为会适用的。
有人可以从C#规范中解释这里发生了什么吗?
Servy有下面的解释,但是你想要做的是:'new List {}' –
或者是'new List()'更好?也许没关系。我想我今天看到一个问题,关于哪两种选择更好,但我现在无法为我的生活找到它。 –