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" }
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
上面的程序编译很好,但在运行时崩溃,而Object引用没有设置为对象的实例.
如果您在上面的代码段中注意到,我在初始化子属性时省略了new.
显然,正确的初始化方法是:
var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { …Run Code Online (Sandbox Code Playgroud)