![](/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.