添加到嵌套列表时为NullReference [英] NullReference when Adding to nested list
问题描述
我上课
public class Gallery
{
public string method { get; set; }
public List<List<object>> gidlist { get; set; }
public int @namespace { get; set; }
}
按钮代码
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;
}
在这里,我得到System.NullReferenceException.如何将项目添加到清单列表中?
Here I get System.NullReferenceException. How to add item to gidlist ?
推荐答案
之所以得到它,是因为现在您在jak中初始化了列表.
You get it because in now place you initialized the list within jak.
您可以:
-
添加一个默认的构造函数并在那里初始化列表:
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; }
}
如果在C#6.0中,则可以使用自动属性初始化程序:
If in C# 6.0 then you can use the auto-property initializer:
public List<List<object>> gidlist { get; set; } = new List<List<object>>()
如果在C#6.0中,并且不希望使用某些构造函数选项 原因:
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;
如果在C#6.0之前,最佳实践将是选项1.如果是6.0或更高版本,则是选项2.
If before C# 6.0 best practice will be option 1. If 6.0 or higher then option 2.
这篇关于添加到嵌套列表时为NullReference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!