这是我的第一个问题。
我在Forms App中有这个代码。我不明白为什么我总是得到一个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; }
}
谢谢=)
答案 0 :(得分:1)
为您的产品类添加构造函数:
class Product
{
public string Name { get; set; }
public Dictionary<string, Position> PositionList { get; set; }
public Product()
{
PositionList = new Dictionary<string, Position>();
}
}
您可以避免空引用异常尝试向空字典添加条目:ProductList["ACAD"].PositionList.Add(position.Name, position);