可能重复:
初始化器语法
演示短代码示例(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" } };
我很惊讶地看到最后一行编译并认为我在看到它在运行时爆炸之前找到了一个漂亮的(虽然不一致)快捷方式。最后一次使用有什么用处吗?