NullReference when Adding to nested list

半世苍凉 提交于 2019-12-25 17:12:11

问题


I have class

public class Gallery
{
    public string method { get; set; }
    public List<List<object>> gidlist { get; set; }
    public int @namespace { get; set; }
}

Button code

private void button1_Click(object sender, EventArgs e)
{
    List<object> data = new List<object>();
    data.Add(618395);
    data.Add("0439fa3666");

    Gallery jak = new Gallery();
    jak.method = "gdata";
    jak.gidlist.Add(data);
    jak.@namespace = 1;

    string json = JsonConvert.SerializeObject(jak);
    textBox2.Text = json;
}

Here I get System.NullReferenceException. How to add item to gidlist ?


回答1:


You get it because in now place you initialized the list within jak.

You can:

  1. Add a default constructor and initialize list there:

    public class Gallery
    {
        public Gallery()
        {
            gidlist = new List<List<object>>();
        }
    
        public string method { get; set; }
        public List<List<object>> gidlist { get; set; }
        public int @namespace { get; set; }
    }
    
  2. If in C# 6.0 then you can use the auto-property initializer:

    public List<List<object>> gidlist { get; set; } = new List<List<object>>()
    
  3. If in under C# 6.0 and don't want the constructor option for some reason:

    private List<List<object>> _gidlist = new List<List<object>>(); 
    public List<List<object>> gidlist 
    {
        get { return _gidlist; } 
        set { _gidlist = value; }
    }
    
  4. You can just initialize it before using (I don't recommend this option)

    Gallery jak = new Gallery();
    jak.method = "gdata";
    jak.gidlist = new List<List<object>>();
    jak.gidlist.Add(data);
    jak.@namespace = 1;
    

If before C# 6.0 best practice will be option 1. If 6.0 or higher then option 2.



来源:https://stackoverflow.com/questions/39016363/nullreference-when-adding-to-nested-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!