【发布时间】:2015-11-27 07:32:47
【问题描述】:
using System;
using System.Collections.Generic;
class Parent
{
public Child Child { get; set; }
}
class Child
{
public List<string> Strings { get; set; }
}
static class Program
{
static void Main() {
// bad object initialization
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
}
}
上述程序编译正常,但在运行时崩溃,对象引用未设置为对象的实例。
如果您在上面的 sn-p 中注意到,我在初始化子属性时省略了 new。
显然正确的初始化方式是:
var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { "hello", "world" }
}
};
我的问题是为什么 C# 编译器在看到第一个构造时没有抱怨?
为什么损坏的初始化有效语法?
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
【问题讨论】: