C# 获取代码中的NullReferenceException

C# 获取代码中的NullReferenceException,c#,nullreferenceexception,C#,Nullreferenceexception,这个代码有什么问题 public partial class MainForm : Form { private Dictionary<String , PropertyInfo[]> types; public MainForm() { //OpenAccountStruct is in the scope types.Add("OpenAccount", new OpenAcco

这个代码有什么问题

public partial class MainForm : Form
 {
        private Dictionary<String , PropertyInfo[]> types;  
        public MainForm()
        {
            //OpenAccountStruct is in the scope
            types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
        }
} 
public分部类MainForm:Form
{
专用词典类型;
公共表格(
{
//OpenAccountStruct在范围内
添加(“OpenAccount”,新的OpenAccountStruct().GetType().GetProperties());
}
} 

为什么我会得到
NullReferenceException

您没有创建
类型的实例(您的字典)

试一试

types=newdictionary();

未初始化
类型
变量。 使用
types=newdictionary()

专用字典类型=
新字典();

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

 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());
        }
} 
public分部类MainForm:Form
{
私有字典类型=新字典();
公共表格(
{
//OpenAccountStruct在范围内
添加(“OpenAccount”,新的OpenAccountStruct().GetType().GetProperties());
}
} 

Put types=new Dictionary();在方法的第一行。基本调试会告诉您,
types
在这里是空引用,因此您的问题与反射几乎没有关系。几乎所有
NullReferenceException
的情况都是相同的。请参阅“”以获得一些提示。可能需要提及的是
types
是字典。
 private Dictionary<String , PropertyInfo[]> types = 
                        new Dictionary<String , PropertyInfo[]>();
 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());
        }
}