在代码中获取NullReferenceException

时间:2011-09-22 07:16:09

标签: c# nullreferenceexception

此代码有什么问题?

public partial class MainForm : Form
 {
        private Dictionary<String , PropertyInfo[]> types;  
        public MainForm()
        {
            //OpenAccountStruct is in the scope
            types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
        }
} 

为什么我会收到NullReferenceException

4 个答案:

答案 0 :(得分:4)

您没有制作types(您的词典)的实例。

types = new Dictionary<String , PropertyInfo[]>();

答案 1 :(得分:1)

types变量未初始化。 使用types = new Dictionary<String , PropertyInfo[]>();

答案 2 :(得分:0)

 private Dictionary<String , PropertyInfo[]> types = 
                        new Dictionary<String , PropertyInfo[]>();

答案 3 :(得分:0)

显然,您的类型字段未初始化,

 public partial class MainForm : Form
 {
        private Dictionary<String , PropertyInfo[]> types = new Dictionary<String , PropertyInfo[]>();
        public MainForm()
        {
            //OpenAccountStruct is in the scope
            types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
        }
}