以下代码抛出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" }
是初始化它的唯一正确方法吗?答案 0 :(得分:3)
谢谢你们。总结集合初始化程序不会创建集合本身的实例,而只是使用Add()将项目添加到existant实例,如果实例不存在则抛出NullReferenceException
1
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
}
public Collection<string> 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<string>();
Items.Add("foo1");
}
public Collection<string> Items { get; private set; }
}
var foo = new Foo()
{
Items = { "foo2" } // foo.Items contains 2 elements: "foo1", "foo2"
};
答案 1 :(得分:1)
在Foo
构造函数中,您要初始化集合。
internal class Foo
{
public Foo(){Items = new Collection(); }
public Collection<string> Items { get; set; } // or List<string>
}
class Program
{
static void Main(string[] args)
{
new Foo()
{
Items = { "foo" } // throws NullReferenceException
};
}
}
答案 2 :(得分:1)
您从未实例化Items
。试试这个。
new Foo()
{
Items = new Collection<string> { "foo" }
};
回答第二个问题:您需要添加构造函数并在那里初始化Items
。
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
}
public Collection<string> Items { get; private set; }
}
答案 3 :(得分:0)
Foo.Items
,但从未分配Collection
的实例,因此.Items
为null
。
修正:
internal class Foo
{
public Collection<string> Items { get; set; } // or List<string>
}
class Program
{
static void Main(string[] args)
{
new Foo()
{
Items = new Collection<string> { "foo" } // no longer throws NullReferenceException :-)
};
}
}