Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - NullReference when Adding to nested list

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...