![](/img/trans.png)
[英]Why the following C# code throws NullReferenceException on nullable DateTime initialization?
[英]Why Collection Initialization Throws NullReferenceException
以下代码抛出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" }
是唯一正确的初始化方法? 多谢你们。 由于摘要集合初始化程序不创建集合本身的实例,而只是使用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"
};
在你的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
};
}
}
你从未实例化过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; }
}
声明了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 :-)
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.