我碰上運行下面的代碼NullReferenceException
例外:接口集合成員的奇怪行爲
public class Container
{
public IList<string> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
var container = new Container() { Items = {"Test"} };
}
}
這是合乎邏輯的compiller無法創建interaface實例,但我得到了一個運行時異常,而不是編譯時。當我進一步調查此行爲時,我更加困惑:
var container = new Container() { Items = {} }; //Legal, Items is null after initialization
var container = new Container() { Items = { "Test" } }; //Legal, throws exception
container.Items = {}; //Illegal doesn't compile
container.Items = {"Test"}; //Illegal doesn't compile
這是某種錯誤還是我不明白? 而我使用.NET Framework 4.0
我一直認爲'var container = new Container(){Items = {「Test」}}'創建集合並添加項目到集合中,我錯了:( – Andrew 2013-03-20 10:31:44