2014-03-12 56 views
0

的情况下我有这样无法将数据添加到模型对象

public class PersonFullResponse 
{ 
    public string profilePicture { get; set; } 
    public string primaryMembership { get; set; } 
    public List<EducationsResponse> educations { get; set; } 
} 
public class EducationsResponse 
{ 
    public string Id { get; set; } 
    public string SchoolName { get; set; } 
    public int StartYear { get; set; } 
    public int EndYear { get; set; } 
    public string Degree { get; set; } 
    public object FieldOfStudy { get; set; } 
} 

两个示范类,你可以看到第一个模型包含第二模型的列表了。 现在我试图创建这个类和数据资料的目的是像这样

PersonFullResponse pfr = new PersonFullResponse(); 
        var er = new EducationsResponse 
       { 
        Degree = "", 
        SchoolName = "", 
        StartYear =11, 
        EndYear =12 
       }; 
      pfr.educations.Add(er); 

但是,这将引发一个错误,在最后步骤

System.NullReferenceException was unhandled by user code 
    HResult=-2147467261 
    Message=Object reference not set to an instance of an object. 

任何一个可以指出我我做错了吗?

回答

2

你应该设置教育清空列表。之后你可以添加成员。

PersonFullResponse pfr = new PersonFullResponse {educations = new List<EducationsResponse>()}; 

然后,您创建PersonFullResponse实例,所有属性都设置为默认值。 List的默认值为null。所以你应该在使用它之前创建List的新实例。

您可以通过setter或类构造函数来设置属性。

+0

我不完全明白你,你可以添加一个代码示例? – Athul

+0

我将代码添加到答案 –

+0

是的,这工作表示感谢您的帮助。我会接受答案作为正确的意思,而可能是你可以添加一些更多的描述到你的答案,这将有助于其他人了解什么出了问题,为什么这解决方案:) – Athul