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" }
}
};
}
}
上面的程序编译得很好,但是在运行时崩溃了未将对象引用设置到对象的实例.
如果您注意到上面的片段,我有省略新的在初始化子属性时。
显然正确的初始化方法是:
var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { "hello", "world" }
}
};
我的问题是为什么 C# 编译器在看到第一个构造时不抱怨?
为什么损坏的初始化有效语法?
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
这不是语法错误,而是您在未实例化的属性上使用了对象初始值设定项。你写的内容可以扩展到
var parent = new Parent();
parent.Child.Strings = new List<string> { "hello", "world" };
这会引发NullReferenceException
:您正在尝试分配该属性Strings
属性所包含的Child
while Child
还是null
。
使用构造函数来实例化Child
首先,解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)