编译器接受抛出 NullReferenceException 的几乎对象初始化程序

发布于 2024-12-01 12:05:48 字数 790 浏览 0 评论 0原文

可能的重复:
初始化语法

演示的简短代码示例(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

待天淡蓝洁白时 2024-12-08 12:05:48

最后一行翻译为:

B tmp = new B();
tmp.a.Name = "foo";
B b = tmp;

是的,它绝对具有实用性 - 当新创建的对象具有返回可变类型的只读属性时。不过,类似功能最常见的用途可能是集合:

Person person = new Person {
    Friends = {
        new Person("Dave"),
        new Person("Bob"),
    }
}

这将从 Person获取朋友列表,并向其中添加两个新人。

The last line is translated to:

B tmp = new B();
tmp.a.Name = "foo";
B b = tmp;

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:

Person person = new Person {
    Friends = {
        new Person("Dave"),
        new Person("Bob"),
    }
}

This will fetch the list of friends from Person and add two new people to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文