using System;
using System.Collections.Generic;
class Parent
{
public Child Child { get; set; }
}
class Child
{
public List<string> Strings { get; set; }
}
static class Program
{
static void Main() {
// bad object initialization
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
}
}
上述程序編譯罰款,但在運行時與對象引用未設置到對象的實例崩潰。沒有「新目錄」初始化列表屬性引起的NullReferenceException
如果你注意到上面的代碼片段,我有在初始化子屬性時省略了新的。
顯然初始化正確的做法是:
var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { "hello", "world" }
}
};
我的問題是,爲什麼C#編譯器不會當它看到第一個構建抱怨嗎?
爲什麼壞了初始化有效語法?
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
啊只讀屬性,謝謝! – Ajai
集合初始化器與只讀屬性無關。此代碼的工作,因爲你把'字符串=新名單();'在構造函數,不是因爲酒店有'私人set'。 –
GSerg
再次閱讀代碼。 Child屬性不是集合,它是隻讀屬性。 –