3
可能重複:
Initializer syntax編譯器接受幾乎對象初始化拋出的NullReferenceException
短代碼示例演示(VS2010 SP1,64位的Win7):
class A
{
public string Name { get; set; }
}
class B
{
public A a { get; set; }
}
// OK
A a = new A { Name = "foo" };
// Using collection initialiser syntax fails as expected:
// "Can only use array initializer expressions to assign
// to array types. Try using a new expression instead."
A a = { Name = "foo" };
// OK
B b = new B { a = new A { Name = "foo" } };
// Compiles, but throws NullReferenceException when run
B b = new B { a = { Name = "foo" } };
我很驚訝地看到最後一行編譯並認爲我找到了一個漂亮的(儘管不一致帳篷)在看到它在運行時炸燬的捷徑。最後一次使用是否有用途?
我以前問過。 – leppie
@leppie所以你做到了!也可以關閉這一個。 – shambulator