以下代码会引发
NullReferenceException
异常:internal class Foo
{
public Collection<string> Items { get; set; } // or List<string>
}
class Program
{
static void Main(string[] args)
{
new Foo()
{
Items = { "foo" } // throws NullReferenceException
};
}
}
- 为什么在这种情况下集合初始化器不起作用,即使
Collection<string>
实现了Add()
方法,为什么会抛出NullReferenceException异常? - 是否有可能让集合初始化器起作用,或者
Items = new Collection<string>() { "foo" }
是初始化它的唯一正确方式?
new
吗? - pennstatephil