问题
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:
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; } }
If in C# 6.0 then you can use the auto-property initializer:
public List<List<object>> gidlist { get; set; } = new List<List<object>>()
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; } }
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