编译器接受抛出 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" } };
我很惊讶地看到最后行编译并认为我找到了一个漂亮的(尽管不一致)快捷方式,然后看到它在运行时崩溃。最后的用法有什么用处吗?
Possible Duplicate:
Initializer syntax
Short code sample to demonstrate (VS2010 SP1, 64-bit 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" } };
I was surprised to see that last line compile and thought I'd found a nifty (though inconsistent) shortcut before seeing it blow up at runtime. Does that last usage have any utility?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后一行翻译为:
是的,它绝对具有实用性 - 当新创建的对象具有返回可变类型的只读属性时。不过,类似功能最常见的用途可能是集合:
这将从
Person
中获取朋友列表,并向其中添加两个新人。The last line is translated to:
And yes, it very definitely has utility - when the newly created object has a read-only property returning a mutable type. The most common use of something similar is probably for collections though:
This will fetch the list of friends from
Person
and add two new people to it.