为什么集合初始化会引发NullReferenceException
以下代码抛出NullReferenceException
:
internal class Foo { public Collection Items { get; set; } // or List } class Program { static void Main(string[] args) { new Foo() { Items = { "foo" } // throws NullReferenceException }; } }
- 为什么收集initiliazers在这种情况下不起作用,虽然
Collection
实现了Add()
方法,为什么抛出NullReferenceException? - 是否可以使集合初始化程序工作,或者是
Items = new Collection() { "foo" }
初始化它的唯一正确方法?
你从未实例化过Items
。 试试这个。
new Foo() { Items = new Collection { "foo" } };
回答你的第二个问题:你需要添加一个构造函数并在那里初始化Items
。
internal class Foo { internal Foo() { Items = new Collection(); } public Collection Items { get; private set; } }
为什么你的代码抛出NullReferenceException ?
多谢你们。 由于摘要集合初始化程序不创建集合本身的实例,而只是使用Add()将项目添加到existant实例 ,如果实例不存在则抛出NullReferenceException
1。
internal class Foo { internal Foo() { Items = new Collection(); } public Collection Items { get; private set; } } var foo = new Foo() { Items = { "foo" } // foo.Items contains 1 element "foo" };
2。
internal class Foo { internal Foo() { Items = new Collection(); Items.Add("foo1"); } public Collection Items { get; private set; } } var foo = new Foo() { Items = { "foo2" } // foo.Items contains 2 elements: "foo1", "foo2" };
在你的Foo
构造函数中,你想初始化集合。
internal class Foo { public Foo(){Items = new Collection(); } public Collection Items { get; set; } // or List } class Program { static void Main(string[] args) { new Foo() { Items = { "foo" } // throws NullReferenceException }; } }
声明了Foo.Items
,但从未分配过Collection
的实例,因此.Items
为null
。
固定:
internal class Foo { public Collection Items { get; set; } // or List } class Program { static void Main(string[] args) { new Foo() { Items = new Collection { "foo" } // no longer throws NullReferenceException :-) }; } }