2016-08-18 87 views
-1

时,我有类NullReference添加到嵌套列表

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); 
    [email protected] = 1; 

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

在这里,我得到System.NullReferenceException。如何将项目添加到gidlist?

+4

可能重复[什么是NullReferenceException,以及如何解决它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how -DO-I-FIX-我t) –

回答

4

你明白了,因为现在你已经初始化了jak中的列表。

您可以:

  1. 添加一个默认的构造函数,有初始化列表:

    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. 如果在C#6.0,那么你可以使用自动属性初始化:

    public List<List<object>> gidlist { get; set; } = new List<List<object>>() 
    
  3. 如果在C#6.0下并且不希望某些的构造函数选项原因:

    private List<List<object>> _gidlist = new List<List<object>>(); 
    public List<List<object>> gidlist 
    { 
        get { return _gidlist; } 
        set { _gidlist = value; } 
    } 
    
  4. 你可以只使用前初始化它(我不建议使用此选项)

    Gallery jak = new Gallery(); 
    jak.method = "gdata"; 
    jak.gidlist = new List<List<object>>(); 
    jak.gidlist.Add(data); 
    [email protected] = 1; 
    

如果说之前的C#6.0的最佳实践将是选项1,如果6.0或更高,然后选项2.

+1

很酷,不知道C#6.0中的自动属性初始值设定项 – Hintham