-1
這是我的第一個問題。C#將屬性設置爲字典列表中的對象 - 爲什麼NullReferenceException?
我的表單應用程序中有此代碼。我不明白爲什麼我總是得到一個NullReferenceException。
public partial class Form1 : Form
{
Dictionary<string, Product> ProductList = new Dictionary<string, Product>();
public Form1()
{
InitializeComponent();
Product product = new Product();
Position position = new Position();
product.Name = "ACAD";
position.Name = "Industry";
ProductList.Add(product.Name, product);
// NullReferenceException:
ProductList["ACAD"].PositionList.Add(position.Name, position);
// Following line works:
//listBox1.Items.Add(ProductList["ACAD"]);
}
}
class Product
{
public string Name { get; set; }
public Dictionary<string, Position> PositionList { get; set; }
}
class Position
{
public string Name { get; set; }
}
謝謝=)
有人必須初始化'Product.PositionList'('= new Dictionary ...') –
PositionList爲null,所以NullReferenceException'Product product = new產品(); product.Name =「ACAD」; product.PositionList = new Dictionary();' –
din
更改'class Product',以便'PositionList'被初始化。你可以寫'公共變種PositionList =新詞典<字符串,位置>()' –