如何将列表填充为类对象?例如,这不起作用:
[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}
public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}
public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
这是控制器动作:
public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();
List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;
return jsonReviewFormFields;
}
代码在
崩溃jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
这可能是一个基本的面向对象错误。你如何填写清单?
答案 0 :(得分:2)
您没有实例化它,您必须首先实例化该类型:
jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();
然后设置它的属性:
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort
之前你还必须实例化我在控制器动作中看不到的主要课程:
JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();