编译器几乎接受抛出NullReferenceException的对象初始值设定项
本文关键字:对象 NullReferenceException 编译器 | 更新日期: 2023-09-27 18:06:30
可能重复:
初始化程序语法
演示的短代码示例(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" } };
看到最后一行的编译,我很惊讶,并认为在看到它在运行时崩溃之前,我已经找到了一个漂亮的(尽管不一致(快捷方式。最后一次使用有用吗?
最后一行被翻译为:
B tmp = new B();
tmp.a.Name = "foo";
B b = tmp;
是的,它肯定有实用性——当新创建的对象有一个只读属性,返回一个可变 这将从Person person = new Person {
Friends = {
new Person("Dave"),
new Person("Bob"),
}
}
Person
中获取朋友列表,并向其中添加两个新人。