3

可能重复:
初始化器语法

演示短代码示例(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" } };

我很惊讶地看到最后一行编译并认为我在看到它在运行时爆炸之前找到了一个漂亮的(虽然不一致)快捷方式。最后一次使用有什么用处吗?

4

1 回答 1

5

最后一行被翻译成:

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

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

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

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

于 2011-08-23T14:22:28.893 回答