當我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()'更好?也許沒關係。我想我今天看到一個問題,關於哪兩種選擇更好,但我現在無法爲我的生活找到它。 –